Draw a JPanel in a Image

Hi,
I'd like to draw what is in my JPanel into a image to export it. But When I try to do that , I have problems. I put my code to be more clear:
// comp is the JPanel
comp.setDoubleBuffered(false);
JFrame frame = new JFrame();
frame.setContentPane(comp);
frame.pack();
Dimension size = comp.getSize();
Image image = comp.createImage(size.width,size.height);
final Graphics g = image.getGraphics();
g.setClip(0,0,size.width,size.height);
try
// Paint the Swing component into the image
SwingUtilities.invokeAndWait(new Runnable()
public void run()
comp.paint(g);
catch (Exception x) { x.printStackTrace(); }
finally
g.dispose();
frame.dispose();
The problem is that I export into GIF this image, but if I don't show the frame:
frame.show(); at least one time, the image is bad: it has a black background. I tried to set the background, but nothing works execpt showing the frame.
If you could help me, I would be great.
Vincent

to diesel22
http://onesearch.sun.com/search/developers/index.jsp?col=devforums&qp=&qt=%2Bprint+%2Bshow

Similar Messages

  • How to draw 2D shapes on the image generated by JMF MediaPlayer?

    Hello all:
    IS there any way that we can draw 2D shapes on the image generated by JMF
    MediaPlayer?
    I am currently working on a project which should draw 2D shapes(rectangle, circle etc) to
    mark the interesting part of image generated by JMF MediaPlayer.
    The software is supposed to work as follows:
    1> first use will open a mpg file and use JMF MediaPlayer to play this video
    2> if the user finds some interesting image on the video, he will pause the video
    and draw a circle to mark the interesting part on that image.
    I know how to draw a 2D shapes on JPanel, however, I have no idea how I can
    draw them on the Mediaplayer Screen.
    What technique I should learn to implement this software?
    any comments are welcome.
    thank you
    -Daniel

    If anyone can help?!
    thank you
    -Daniel

  • How can I draw on top of an image?

    I'm using a JApplet with three JPanel's inside of it.
    Inside one of those JPanel's I would like to place an image and a button. When the button is clicked, I want to draw an oval on top of the image . Each subsequent time the button is clicked, the oval will move to a different location.
    So here are my questions:
    1) What should I use to draw the image? (a JLabel with an ImageIcon on it?)
    2) Could I simply use g.drawOval() in paintComponent() to directly draw on top of the image/JLabel?
    Any help will be greatly appriciated.

    Here's a sample to study;-import java.awt.*;
    import java.awt.event.*;
    public class DrawOnImage extends java.applet.Applet{
      int xPos, yPos;
      Image img;
      public void init() {
        add(new Label("Hello World") );
        Button press = new Button("press");
        add(press);
        press.addActionListener(new ActionListener(){
          public void actionPerformed(ActionEvent e){
            xPos = (int)(Math.random()*270);
            yPos = (int)(Math.random()*170)+30;
            repaint();
        img = getImage(getDocumentBase(), "anImage.JPG");
      public void paint(Graphics g){
        g.drawImage(img,0,30,this);
        if(yPos>=30)g.fillOval(xPos, yPos, 45, 45);
    }

  • Drawing on top of an image

    Hello!
    I am trying to create a Panel on which I can draw stuff using the mouse. I have managed to get it working, apart from one small part. I want to have an image (jpg) as a background, and as soon as I try to add an image either the image does not show or the drawing stuff stops working.
    Here is my working drawing code (i.e. without image):
    public void paintComponent(Graphics g) {
             super.paintComponent(g);
             if (image == null || image.getWidth(null) != getWidth()
                   || image.getHeight(null) != getHeight()) {
                image = (BufferedImage) createImage(getWidth(), getHeight());
                graph = (Graphics2D) image.getGraphics();
                graph.fillRect(0, 0, getWidth(), getHeight());
                graph.setColor( Color.white );
                graph.setStroke(new BasicStroke(3));
                graph.addRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING,
                      RenderingHints.VALUE_ANTIALIAS_ON));
             Rectangle r = g.getClipBounds();
             g.drawImage(image, r.x, r.y, r.x + r.width, r.y + r.height, r.x, r.y,
                   r.x + r.width, r.y + r.height, null);
             if (endPoint != null) {
                g.setColor(currentColor);
                if (shapeType == 0)
                   g.drawLine(startPoint.x, startPoint.y, endPoint.x, endPoint.y);
                if (shapeType == 1)
                   g.drawOval(pn.x, pn.y, pn.width, pn.height);
                if (shapeType == 2)
                   g.drawRect(pn.x, pn.y, pn.width, pn.height);
             public void mouseDragged( MouseEvent m ) {
                if (shapeType > 3 && shapeType != 8)
                   return;
                if (endPoint == null)
                   endPoint = new Point();
                repaint(pn.x, pn.y, pn.width + 1, pn.height + 1);
                pn.x = Math.min(startPoint.x, m.getX());
                pn.y = Math.min(startPoint.y, m.getY());
                pn.width = Math.abs(m.getX() - startPoint.x);
                pn.height = Math.abs(m.getY() - startPoint.y);
                if (shapeType == 0) {
                   endPoint.setLocation(m.getPoint().getLocation());
                if (shapeType == 3) {
                   graph.setColor(currentColor);
                   graph.drawLine(startPoint.x, startPoint.y, m.getX(), m.getY());
                   startPoint = m.getPoint();
                repaint(pn.x, pn.y, pn.width + 1, pn.height + 1);
             public void mouseReleased(MouseEvent m) {
                if (endPoint != null)
                   draw();
                endPoint = null;
             public void mousePressed(MouseEvent m) {
                startPoint = m.getPoint();
             public void draw() {
                graph.setColor(currentColor);
                if (shapeType == 0)
                   graph.drawLine(startPoint.x, startPoint.y, endPoint.x, endPoint.y);
                if (shapeType == 1)
                   graph.drawOval(pn.x, pn.y, pn.width, pn.height);
                if (shapeType == 2)
                   graph.draw(pn);
                repaint(pn.x, pn.y, pn.width + 1, pn.height + 1);
             }To me it seemed logical to add:
    graph.drawImage(my_gif, 0, 0, this);at the end of the if statement, but that did not work.
    Where and how should I add the image?
    Thanks!

    Thanks for answering!
    Here is the entire code:
    import java.awt.BasicStroke;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Image;
    import java.awt.Point;
    import java.awt.Rectangle;
    import java.awt.RenderingHints;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseMotionListener;
    import java.awt.image.BufferedImage;
    import javax.swing.JApplet;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    @SuppressWarnings("serial")
    public class ImageExample extends JApplet {
       private static final Dimension DRAWING_AREA_SIZE = new Dimension(300,300);
       private static final Point DRAWING_AREA_UPPER_LEFT = new Point(100,50);
       private static final Color BACKGROUND_COLOR = Color.black;
       private Image my_gif;
       private Color currentColor = Color.white;
       private JLabel currentColorIndicator;
       private JPanel pane = new JPanel(null);
       Point startPoint, endPoint;
       Rectangle pn = new Rectangle();
       BufferedImage image;
       Graphics2D graph;
       int shapeType = 3;
       public void init() {
          setContentPane(pane);
          my_gif = getImage( getDocumentBase(), "fractal.gif" );
          pane.setOpaque(true);
          pane.setBackground(BACKGROUND_COLOR);
          createColorMap();
          DrawingPanel drawingPanel = new DrawingPanel();
          drawingPanel.setBounds(DRAWING_AREA_UPPER_LEFT.x, DRAWING_AREA_UPPER_LEFT.y, DRAWING_AREA_SIZE.width,
                DRAWING_AREA_SIZE.height);
          pane.add(drawingPanel);
       // Private methods
       private void createColorMap() {
          ColorPickerListener listener = new ColorPickerListener();
          JLabel colorText = new JLabel("Color");
          colorText.setBounds(10, DRAWING_AREA_UPPER_LEFT.y-20, 50, 25);
          colorText.setForeground(Color.white);
          pane.add(colorText);
          JLabel redColor = new JLabel("");
          redColor.addMouseListener(listener);
          redColor.setBackground(Color.RED);
          redColor.setBounds(10, DRAWING_AREA_UPPER_LEFT.y+10, 50, 30);
          redColor.setOpaque(true);
          pane.add(redColor);
          JLabel blueColor = new JLabel("");
          blueColor.addMouseListener(listener);
          blueColor.setBackground(Color.blue);
          blueColor.setBounds(10, DRAWING_AREA_UPPER_LEFT.y+40, 50, 30);
          blueColor.setOpaque(true);
          pane.add(blueColor);
          JLabel whiteColor = new JLabel("");
          whiteColor.addMouseListener(listener);
          whiteColor.setBackground(Color.white);
          whiteColor.setBounds(10, DRAWING_AREA_UPPER_LEFT.y+70, 50, 30);
          whiteColor.setOpaque(true);
          pane.add(whiteColor);
          JLabel greenColor = new JLabel("");
          greenColor.addMouseListener(listener);
          greenColor.setBackground(Color.green);
          greenColor.setBounds(10, DRAWING_AREA_UPPER_LEFT.y+100, 50, 30);
          greenColor.setOpaque(true);
          pane.add(greenColor);
          JLabel blackColor = new JLabel("");
          blackColor.addMouseListener(listener);
          blackColor.setBackground(Color.black);
          blackColor.setBounds(10, DRAWING_AREA_UPPER_LEFT.y+130, 50, 30);
          blackColor.setOpaque(true);
          pane.add(blackColor);
          JLabel grayColor = new JLabel("");
          grayColor.addMouseListener(listener);
          grayColor.setBackground(Color.gray);
          grayColor.setBounds(10, DRAWING_AREA_UPPER_LEFT.y+160, 50, 30);
          grayColor.setOpaque(true);
          pane.add(grayColor);
          JLabel yellowColor = new JLabel("");
          yellowColor.addMouseListener(listener);
          yellowColor.setBackground(Color.yellow);
          yellowColor.setBounds(10, DRAWING_AREA_UPPER_LEFT.y+190, 50, 30);
          yellowColor.setOpaque(true);
          pane.add(yellowColor);
          // Display currently chosen color
          JLabel currentColorText = new JLabel("Current");
          currentColorText.setBounds(10, DRAWING_AREA_UPPER_LEFT.y+230, 50, 25);
          currentColorText.setForeground(Color.white);
          pane.add(currentColorText);
          currentColorIndicator = new JLabel("");
          currentColorIndicator.setBounds(10, DRAWING_AREA_UPPER_LEFT.y+260, 50, 30);
          updateCurrentColorLabel();
          currentColorIndicator.setOpaque(true);
          pane.add(currentColorIndicator);
       private void updateCurrentColorLabel() {
          currentColorIndicator.setBackground(currentColor);
          currentColorIndicator.setForeground(new Color(255 - currentColor.getRed(), 255 - currentColor.getGreen(),
                255 - currentColor.getBlue()));
       // Private classes
       private class DrawingPanel extends JPanel implements MouseListener, MouseMotionListener {
          BufferedImage image;
          public DrawingPanel() {
             addMouseMotionListener(this);
             addMouseListener(this);
          public void paintComponent(Graphics g) {
             super.paintComponent(g);
             if (image == null || image.getWidth(null) != getWidth()
                   || image.getHeight(null) != getHeight()) {
                image = (BufferedImage) createImage(getWidth(), getHeight());
                graph = (Graphics2D) image.getGraphics();
                graph.fillRect(0, 0, getWidth(), getHeight());
                graph.setColor( Color.white );
                graph.setStroke(new BasicStroke(3));
                graph.addRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING,
                      RenderingHints.VALUE_ANTIALIAS_ON));
                graph.drawImage(my_gif, 0, 0, this);
                System.out.println(my_gif + " <- my_gif");
                System.out.println(my_gif.getWidth(this) + " <- my_gif.getWidth(this)");
                System.out.println(my_gif.getHeight(this) + " <- my_gif.getheight(this)");
             Rectangle r = g.getClipBounds();
             g.drawImage(image, r.x, r.y, r.x + r.width, r.y + r.height, r.x, r.y,
                   r.x + r.width, r.y + r.height, null);
             if (endPoint != null) {
                g.setColor(currentColor);
                if (shapeType == 0)
                   g.drawLine(startPoint.x, startPoint.y, endPoint.x, endPoint.y);
                if (shapeType == 1)
                   g.drawOval(pn.x, pn.y, pn.width, pn.height);
                if (shapeType == 2)
                   g.drawRect(pn.x, pn.y, pn.width, pn.height);
             public void mouseDragged( MouseEvent m ) {
                if (shapeType > 3 && shapeType != 8)
                   return;
                if (endPoint == null)
                   endPoint = new Point();
                repaint(pn.x, pn.y, pn.width + 1, pn.height + 1);
                pn.x = Math.min(startPoint.x, m.getX());
                pn.y = Math.min(startPoint.y, m.getY());
                pn.width = Math.abs(m.getX() - startPoint.x);
                pn.height = Math.abs(m.getY() - startPoint.y);
                if (shapeType == 0) {
                   endPoint.setLocation(m.getPoint().getLocation());
                if (shapeType == 3) {
                   graph.setColor(currentColor);
                   graph.drawLine(startPoint.x, startPoint.y, m.getX(), m.getY());
                   startPoint = m.getPoint();
                repaint(pn.x, pn.y, pn.width + 1, pn.height + 1);
             public void mouseReleased(MouseEvent m) {
                if (endPoint != null)
                   draw();
                endPoint = null;
             public void mousePressed(MouseEvent m) {
                startPoint = m.getPoint();
             public void draw() {
                graph.setColor(currentColor);
                if (shapeType == 0)
                   graph.drawLine(startPoint.x, startPoint.y, endPoint.x, endPoint.y);
                if (shapeType == 1)
                   graph.drawOval(pn.x, pn.y, pn.width, pn.height);
                if (shapeType == 2)
                   graph.draw(pn);
                repaint(pn.x, pn.y, pn.width + 1, pn.height + 1);
             public void mouseClicked(MouseEvent arg0) {}
             public void mouseEntered(MouseEvent arg0) {         }
             public void mouseExited(MouseEvent arg0) {         }
             public void mouseMoved(MouseEvent arg0) {         }
       //Listeners
       private class ColorPickerListener extends MouseAdapter {
          public void mouseClicked(MouseEvent e) {
             JLabel color = (JLabel) e.getSource();
             currentColor = color.getBackground();
             updateCurrentColorLabel();
    }So the problem might be that the system.outs in there put out:
    sun.awt.image.ToolkitImage@1a0c10f <- my_gif
    -1 <- my_gif.getWidth(this)
    -1 <- my_gif.getheight(this)I don't know how to fix so that the height and width are set. Isn't it enough to do the:
          my_gif = getImage( getDocumentBase(), "fractal.gif" );before initializing the drawing panel?
    Thanks again!

  • Saving a JPanel as an image

    Hi peeps,
    I've written the following code after reading many threads about how to save a JPanel as an image. On the whole, it works. But the JPanel itself contains many different bits such as Line2D objects and other shapes, as well as ImageIcons. So when the JPanel is saved, the shape objects save ok but the icons do not get saved. Does anyone know a better solution please?
    By the way: "area" is the var name for a JPanel and "toSave" is a File object in the code below...
    BufferedImage image = new BufferedImage(maxHorizontal, maxVertical, BufferedImage.TYPE_INT_RGB);
    Graphics2D g = image.createGraphics();
    g.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS,RenderingHints.VALUE_FRACTIONALMETRICS_ON);
    g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
    area.paint(g);
    g.dispose();
    ImageIO.write(image, "jpeg", toSave);

    A robot wouldn't do what the OP wanted: with antialiasing, etc...
    I'm still not convinced that ImageIcons don't get saved. Why does this code work:
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import java.io.*;
    import java.net.*;
    import javax.imageio.*;
    import javax.swing.*;
    public class X {
        public static void main(String[] args) throws IOException {
            final JPanel p = new JPanel();
            p.add(new JLabel(new ImageIcon(new URL("http://today.java.net/jag/bio/JagHeadshot-small.jpg"))));
            p.add(new JLabel(new ImageIcon(new URL("http://java.sun.com/placeholders/duke_swinging.gif"))));
            p.add(new JLabel("etc"));
            JButton save = new JButton("save");
            save.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent evt) {
                    save(p, new File("junk.jpeg"));
            JFrame f = new JFrame("X");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            Container cp = f.getContentPane();
            cp.add(p);
            cp.add(save, BorderLayout.SOUTH);
            f.pack();
            f.setLocationRelativeTo(null);
            f.setVisible(true);
        static void save(Component comp, File file) {
            try {
                BufferedImage image = new BufferedImage(comp.getWidth(), comp.getHeight(), BufferedImage.TYPE_INT_RGB);
                Graphics2D g = image.createGraphics();
                g.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS,RenderingHints.VALUE_FRACTIONALMETRICS_ON);
                g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
                comp.paint(g);
                g.dispose();
                ImageIO.write(image, "jpeg", file);
                image.flush();
            } catch (IOException e) {
                e.printStackTrace();
    }

  • Saving a character displayed on JPanel as an image

    Hi,
    Merry christmas!
    I am new to Java programming. Please englighten me with the following problem I am facing currently.
    I have been trying to save a chinese character displayed on a JPanel as an image. However, what I do not understand is that when the image is saved, it only captured the JPanel (and its background) instead of the character displayed on it.
    The following is my codes for this problem:
    static String strUTF16 = null;
    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                        
    File f = new File("c:\\"+ jTextField2.getText()+ ".JPEG");
    jPanel1.setVisible(true);
    Image capture = jPanel4.createImage(jPanel4.getWidth(),jPanel4.getHeight());
         Graphics g = capture.getGraphics();
    jPanel4.paint(g);
    if(jTextField2.getText() != null)
    try {
                   FileOutputStream out = new FileOutputStream(f);
                   BufferedImage image = null;
                   image = (BufferedImage)capture;
                   if (image != null) {
                        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
                        JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(image);
                        param.setQuality(0.5f,true);
                        encoder.encode(image, param);
                        out.flush();
                        out.close();
              } catch (IOException e) {
                   System.out.println("Error, file cannot be written!\n");
    Any kind advices are greatly appreciated.
    Thanks!
    Shoker

    If you need further help then you need to create a [url http://homepage1.nifty.com/algafield/sscce.html]Short, Self Contained, Compilable and Executable, Example Program (SSCCE) that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.
    And don't forget to use the [url http://forum.java.sun.com/help.jspa?sec=formatting]Code Formatting Tags so the code retains its original formatting.

  • Draw a rectangle on an image in an applet

    Hello
    I have an applet that has 3 buttons. Each of them creates an image, which is displayed on the screen. Now, I want to draw a rectangle on these images. Since I already have a paint method for displaying the images correctly, I would need a second paint method for the rectangle. (I can't put everything in the same paint() method, because I have an horrible resukt)
    Does anyone have an idea of a method that would be able to replace a paint method?
    Any help would be appreciated
    Thanks
    Philippe

    Have you thought about using one of your button to get the action done? You could use the Graphics method to create your object rectangle.
    Don't know if it would work but seems like a good idea to try.

  • How to draw an arc in the image window?

    Now I try to draw an arc in the image window, but when I try to use IMAQ Overlay Arc.vi, it need Bounding Rectangle that made a problem because the arc I draw has a big size whose bounding rectangle was out of the image window. What should I do?

    Hello,
    Bounding rectangle parameters will allow you to enter larger values than your image size as well as negative numbers in order to position your arc properly.
    I hope this helps!
    Regards,
    Yusuf C.
    Applications Engineering
    National Instruments

  • Please help with a drawing on JPanel in a background.

    Hello everybody,
    I have already post this question in the main java forum and was adviced to place the question here. Since then, I have refactored the code. I need your opinion and advice.
    My task is to draw some objects on the JPanel or some other components and to place the names to the objects, for example squares, but later, from the thread. Because it can take some time, untill the names will be avaliable.
    So, I refactored the code I post before http://forum.java.sun.com/thread.jspa?threadID=5192586&tstart=15
    And now, it draws on layers and from thread on resize, with some imitating interval.
    Is it a good approach I use, is there a better way, to draw on JPanel, after some objects were already painted.
    Here is my sample, try to resize window:
    package test;
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Point;
    import java.awt.Rectangle;
    import java.awt.event.ComponentEvent;
    import java.awt.event.ComponentListener;
    import java.awt.geom.Rectangle2D;
    import javax.swing.JFrame;
    import javax.swing.JLayeredPane;
    import javax.swing.JPanel;
    public class Painter extends JFrame implements ComponentListener{
         private static final long serialVersionUID = 1L;
         private ThreadPainter threadPainter;
         JPanel panel = new JPanel() {
              private static final long serialVersionUID = 1L;
              @Override
              protected void paintComponent(Graphics g) {
                   super.paintComponent(g);
                   System.out.println("repaint");
                   Graphics2D g2d = (Graphics2D) g;
                   g2d.setColor(Color.gray);
                   g2d.fillRect(0, 0, 800, 600);
                   g2d.setColor(Color.white);
                   for (int i = 0; i < 6; i++) {
                        Rectangle2D rec2d = new Rectangle2D.Double(10 + i * 100,
                                  10 + i * 100, 10, 10);
                        g2d.fill(rec2d);
                        g2d.drawString("Square " + i, 10 + i * 100 + 20, 10 + i * 100);
                   // start thread to paint some changes later
                   if (threadPainter == null) {
                        threadPainter = new ThreadPainter();
                        threadPainter.start();
         JPanelTest panel1 = new JPanelTest();
         public class JPanelTest extends JPanel {
              private static final long serialVersionUID = 1L;
              private int times = 0;
              @Override
              protected void paintComponent(Graphics g) {
                   super.paintComponent(g);
                   Graphics2D g2d = (Graphics2D) g;
                   g2d.setColor(Color.red);
                   System.out.println("repaint panel test");
                        System.out.println("repaitn times");
                        g2d.drawString("Square " + times, 10 + times * 100 + 20, 10 + times * 100);
              public void repaintMethod(int times) {
                   this.times = times;
                   this.repaint(times * 100 + 20, times * 100, 300,300);
         public class ThreadPainter extends Thread {
              private boolean stop = false;
              @Override
              public void run() {
                   while (!stop) {
                        int cnt = 0;
                        for (int i = 0; i < 6; i++) {
                             System.out.println("do task");
                             panel1.repaintMethod(i);
                             // load data, do calculations
                             try {
                                  // emulate calcilation
                                  Thread.sleep(1000);
                             } catch (InterruptedException e) {
                                  e.printStackTrace();
                             if (stop) {
                                  break;
                             cnt++;
                        if (cnt == 6) {
                             stopThread();
              public void stopThread() {
                   this.stop = true;
         public Painter() {
              this.setLayout(new BorderLayout());
              JLayeredPane pane = new JLayeredPane();
              this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              this.setLocation(new Point(100, 100));
              this.setPreferredSize(new Dimension(800, 600));
              this.panel.setOpaque(false);
              this.panel1.setOpaque(false);
              pane.setOpaque(false);
              pane.add(panel, JLayeredPane.DEFAULT_LAYER);
              pane.add(panel1, new Integer(
                        JLayeredPane.DEFAULT_LAYER.intValue() + 1));
              this.add(pane, BorderLayout.CENTER);
              panel.setBounds(new Rectangle(0, 0, 800, 600));
              panel1.setBounds(new Rectangle(0, 0, 800, 600));
              this.addComponentListener(this);
         public static void main(String[] args) {
              Painter painter = new Painter();
              painter.pack();
              painter.setVisible(true);
         @Override
         public void componentHidden(ComponentEvent e) {
              // TODO Auto-generated method stub
         @Override
         public void componentMoved(ComponentEvent e) {
              // TODO Auto-generated method stub
         @Override
         public void componentResized(ComponentEvent e) {
              if (threadPainter != null) {
                   threadPainter.stopThread();
                   threadPainter = new ThreadPainter();
                   threadPainter.start();
         @Override
         public void componentShown(ComponentEvent e) {
              // TODO Auto-generated method stub
    }

    Hello camickr,
    thanks for your answers.
    It sounds like you are trying to add a component and
    descriptive text of this component to a panel. So the
    question is why are you overriding paintComponent()
    method on your main panel and why are you using a
    Thread.JLabel is not a good way I think, because of the performance. Think about 1000 labels on the panel. And the text can have different style, so drawString method is better here.
    Create a component that draws your "shape" and then
    add that component to the main panel that uses a null
    layout. That means you need to specify the bounds of
    the component. Then you can add a JLabel containing
    the releated text of the component. If you don't know
    the text then it can always be updated with the
    setText() method in the future. Also, the foreground
    can be updated as well.If it would be lable, I could update Text as us say and JLabels would be perfect. In this case, JLabels are not what I need.
    You said the names will not be available right away.
    Well then you don't start a thread to schedule the
    repainting of the names since you don't know exactly
    when the name will be available. You wait until you
    have the names and then simple use the setText()
    method.I have decided this way.
    Draw all objects on the panel in different layers, for different type of objects.
    Get names and make some calculations, for example, optimal position of the text on the panel (in Thread) and after it repaint();
    Repaint draw all objects, but now it have the names, which will be added too.
    The requirement is: thousand of objects on the panel
    Different type of ojbects should be drawn in different layers
    Names should be added to the objects and maybe some other drawings (showing state). Name and drawing can be done later, but should be added dynamically, after all calculation are done.

  • Drawing in JPanel within JApplet

    Hi, having problems drawing in jpanel that is within japplet.
    My code follows:
    * TestApplet.java
    * @author WhooHoo
    //<applet code="TestApplet.class" width="400" height="250"></applet>
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import java.awt.Graphics;
    import javax.swing.JButton;
    public class TestApplet extends javax.swing.JApplet implements ActionListener {
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel1;
    private Graphics g;
    private javax.swing.JButton btnTest;
    /** Creates new form Cafe */
    public TestApplet() {
    public void init() {
    jPanel1 = new javax.swing.JPanel();
    btnTest = new javax.swing.JButton();
    jPanel2 = new javax.swing.JPanel();
    btnTest.setText("test");
    jPanel1.add(btnTest);
    getContentPane().add(jPanel1, java.awt.BorderLayout.NORTH);
    jPanel2.setBorder(new javax.swing.border.TitledBorder("Draw"));
    getContentPane().add(jPanel2, java.awt.BorderLayout.CENTER);
    btnTest.addActionListener(this);
    jPanel2.setOpaque(false);
    g=jPanel2.getGraphics();
    /** Invoked when an action occurs.
    public void actionPerformed(ActionEvent e) {
    if (e.getActionCommand().equalsIgnoreCase("test"))
    System.out.println("test");
    g.setColor(java.awt.Color.BLACK);
         g.drawString("testing",50,50);
         g.drawString("testing",50,100);
         g.drawString("testing",50,150);
         g.drawString("testing",50,200);
         g.drawString("testing",50,250);
    public void destroy()
    g.dispose();
    When this code is run the applet seems to run fine but when the button is pressed, nothing is drawn in jpanel. Can anyone see what the problem is and suggest a fix. I need to be able to pass graphics obj around to other methods to draw in the other methods also. Testing will not dispaly anywhere in applet or frame.
    plz email or post any suggestions.

    but if I can get this to workYou can get this to work, here is the working code:
    import java.awt.event.*;
    import java.awt.Graphics;
    import javax.swing.*;
    import java.awt.*;
    public class TestApplet extends JApplet implements ActionListener {
         private JPanel jPanel2,jPanel1;
         private javax.swing.JButton btnTest;
         String string1 = "";
         public TestApplet() {
         public void init() {
              jPanel1 = new JPanel();
              btnTest = new JButton();
              jPanel2 = new JPanel(){
                   public void paintComponent(Graphics g) {
                        g.setColor(java.awt.Color.BLACK);
                        g.drawString(string1,50,50);
                        g.drawString(string1,50,100);
                        g.drawString(string1,50,150);
                        g.drawString(string1,50,200);
                        g.drawString(string1,50,250);
              btnTest.setText("test");
              jPanel1.add(btnTest);     
              getContentPane().add(jPanel1, BorderLayout.NORTH);
              jPanel2.setBorder(new javax.swing.border.TitledBorder("Draw"));
              getContentPane().add(jPanel2, BorderLayout.CENTER);
              btnTest.addActionListener(this);
              jPanel2.setOpaque(false);
         public void actionPerformed(ActionEvent e) {
              if (e.getActionCommand().equalsIgnoreCase("test"))
                   System.out.println("test");
                   string1 = "testing";
                   jPanel2.repaint();
         public void destroy(){}
    }Unfortunately all painting to a component must happen inside the paint method. I don't know if what you ask is possible. I try to figure it out. Maybe someone else has an answer.
    Pandava

  • Is it possible to draw shapes on an background image?

    Hi all,
    I wanna ask if it is possible for loading an jpg as background image in Canvas, and draw shapes(ovals/rectangles) on it?
    I've tried, but it seems the shapes always covered by the image. How can I due with this? I want the shapes drawn on top of the image, not underneath it.
    Please Help! Thx.

    Am I doing anything wrong? cos I've already draw the shapes after the image in the paint method.
    Here's some of the program coding:
    // init
    PictCanvas coffeeCanvas=new PictCanvas();
    //set up Picture Canvas
    coffeeCanvas.thePic=getImage(getCodeBase(),"50p.jpg");
    coffeeCanvas.setSize(200,200);
    // paint method
    public void paint(Graphics g)
    g.drawImage(thePic,0,0,this);
    g.drawOval(0,0,20,20);
    repaint();
    }

  • Resize of Drawing in JPanel

    Hi,
    I am looking for some ideas on how to resize a drawing in JPanel.
    I wanted to increase its width and height at run time by dragging its end points (any direction).
    One more thing is how do I add text to the drawing at run time? Is this possible?
    My idea is to develop an application similar to MS-Word where we can add few drawings and add text to them.
    Any help would be great.
    Mathew

    The drawing code has to be written in ratios. Don't draw from x1, y1, to x2, y2 -- draw from (left + .3*width, top + .3 * height) to . . . Then the drag gesture should give you new width and height values, and you can just repaint().

  • How to draw a JPanel in an offscreen image

    I am still working on painting a JPanel on an offline image
    I found the following rules :
    - JPanel.setBounds shall be called
    - the JPanel does not redraw an offline image, on should explicitly override paint()
    to paint the children components
    - the Children components do not pain, except if setBounds is called for each of them
    Still with these rules I do not master component placement on the screen. Something important is missing. Does somebody know what is the reason for using setBounds ?
    sample code :
    private static final int width=512;
    private static final int height=512;
    offScreenJPanel p;
    FlowLayout l=new FlowLayout();
    JButton b=new JButton("Click");
    JLabel t=new JLabel("Hello");
    p=new offScreenJPanel();
    p.setLayout(l);
    p.setPreferredSize(new Dimension(width,height));
    p.setMinimumSize(new Dimension(width,height));
    p.setMaximumSize(new Dimension(width,height));
    p.setBounds(0,0,width,height);
    b.setPreferredSize(new Dimension(40,20));
    t.setPreferredSize(new Dimension(60,20));
    p.add(t);
    p.add(b);
    image = new java.awt.image.BufferedImage(width, height,
    java.awt.image.BufferedImage.
    TYPE_INT_RGB);
    Graphics2D g= image.createGraphics();
    // later on
    p.paint(g);
    paint method of offScreenPanel :
    public class offScreenJPanel extends JPanel {
    public void paint(Graphics g) {
    super.paint(g);
    Component[] components = getComponents();
    for (int i = 0; i < components.length; i++) {
    JComponent comp=(JComponent) components;
    comp.setBounds(0,0,512,512);
    components[i].paint(g);

    Unfortunately using pack doesn't work, or I didn't use it the right way.
    I made a test case, eliminated anything not related to the problem (Java3D, applet ...). In the
    test case if you go to the line marked "// CHANGE HERE" and uncomment the jf.show(), you have
    an image generated in c:\tmp under the name image1.png with the window contents okay.
    If you replace show by pack you get a black image. It seems there still something.
    simplified sample code :[b]
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import com.sun.j3d.utils.applet.*;
    import com.sun.j3d.utils.image.*;
    import com.sun.j3d.utils.universe.*;
    import java.io.*;
    import java.awt.image.*;
    import javax.imageio.*;
    public class test {
    private static final int width=512;
    private static final int height=512;
    public test() {
    JPanel p;
    BorderLayout lay=new BorderLayout();
    java.awt.image.BufferedImage image;
    // add a JPanel with a label and a button
    p=new JPanel(lay);
    p.setPreferredSize(new Dimension(width,height));
    JLabel t=new JLabel("Hello");
    t.setPreferredSize(new Dimension(60,20));
    p.add(t,BorderLayout.NORTH);
    p.setDebugGraphicsOptions(DebugGraphics.LOG_OPTION );
    // show the panel for debug
    JFrame jf=new JFrame();
    jf.setSize(new Dimension(width,height));
    jf.getContentPane().add(p);
    [b]
    // CHANGE HERE->
    jf.pack();
    //jf.show();
    // create an off screen image
    image = new java.awt.image.BufferedImage(width, height,
    java.awt.image.BufferedImage.TYPE_INT_RGB);
    // paint JPanel on off screen image
    Graphics2D g= image.createGraphics();
    g.setClip(jf.getBounds());
    System.err.println("BEFORE PAINT");
    jf.paint(g);
    System.err.println("AFTER PAINT");
    // write the offscreen image on disk for debug purposes
    File outputFile = new File("c:\\tmp\\image1.png");
    try {
    ImageIO.write(image, "PNG", outputFile);
    } catch (Exception e) {
    System.err.println(e.getMessage());
    g.dispose();
    jf.dispose();
    public static void main(String[] args) {
    test t=new test();
    }

  • Drawing the contents of JPanel into an image file

    I have the following code and it generates a jpg file but for some reason its not working (i open the jpg file with microsoft paint and i see nothing):
    JPanel panel = new JPanel();
    panel.setLayout(new BorderLayout());
    panel.setPreferredSize(new Dimension(700, 500));
    panel.add(webBrowser, BorderLayout.CENTER);  //WebBrowser is a subclass of JPanel
    BufferedImage img = new BufferedImage(1500, 1500, BufferedImage.TYPE_INT_RGB);
    panel.paint(img.getGraphics());
    try{
         JPEGImageEncoder enc = JPEGCodec.createJPEGEncoder(new FileOutputStream("c:\\haha.jpg"));  
    }catch(FileNotFoundException ex) {
        System.out.println(ex.getMessage());
    }So what's wrong ?? why its not writing the output file correctly ??

    Got it ...i just forgot the 3rd line:
    fos = new FileOutputStream("c:\\majjooo.jpg");
    JPEGImageEncoder enc = JPEGCodec.createJPEGEncoder(fos);
    enc.encode(img);but am still having a problem is that the picture is black ...eventhough the panel has contents and i can see it but the picture has nothing but pitch black ...what do you think ??

  • Convert JPanel to buffered Image

    Hi,
    i have a JPanel,I override the paintComponent() method to do a lot of painting. the size of this panel is about 2500 X 2500 i want to convert it to a buffered image,
    but i dont get image of total panel, but only the image of what is displayed on screen, every thing else is black, i guess becuase this is not painted,
    so how do i get the total image, need help
    this is my code for creating image
    JFrame frame new JFrame();
    frame.getContentPane().add(myPanel);
    this.setSize(1000,700);
    show();
    int iWidth = myPanel.getPreferredSize().width;
    int iHeight =myPanel.getPreferredSize().height;
    BufferedImage image = new BufferedImage(iWidth, iHeight, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = image.createGraphics();
    myPanel.paint(g2);
    try
         ImageIO.write(image, "jpeg", new File("example.jpeg"));
    catch (Exception e) {
    e.printStackTrace();
    }Ashish

    i use this    chartPanel = new JPanel() {
          public void paint(Graphics g) {
            Image img = paintGraph(chartPanel.getWidth(), scroller.getViewport().getHeight());
            g.drawImage(img, 0, 0, Color.white, null);
      protected Image paintGraph(int width, int height) {
        if ((offscreen == null) || (width != offscreensize.width) || (height != offscreensize.height)) {
          offscreen = createImage(width, height);
          offscreensize = new Dimension(width, height);
          offgraphics = (Graphics2D)offscreen.getGraphics();
          try {
            offgraphics.setClip(0, 0, width, height);
            drawChart(offgraphics, width, height);
            offgraphics.setXORMode(offgraphics.getBackground());
            drawSelectables(offgraphics, width, height);
          } catch (ArrayIndexOutOfBoundsException e) { /* we have no data */ }
        return offscreen;
      }where scroller is my JScrollPane() and i get the complete panel to draw on.
    thomas

Maybe you are looking for

  • Error message when I try to download 1.2

    Currently I'm running windows and my itunes finds my ipod and has for sometime now. I currently have verison 1.1.1 and when I try to update to 1.2 through itunes I get this message: Itunes could not contact the Ipod software update server because you

  • Unable to figure out paper sizes in PSE 9...

    Hi, I am trying to print a 4x6 photo... when I click print the pse print window opens and asks to select: printer, paper size & print size.  I don't know what paper sizes they are offering, ex: KG, KG.NMg,  PhotoPaper2L, PhotoPaper2L.NMgn, PhotoPaper

  • Extractor enhancement with user exit RSAP0001

    Hello, I am using user exit RSAP0001 to enhance SAP business partner extractors. When I am processing the data pack in function module EXIT_SAPLRSAP_002, is there any chance to get information about the receiving BI system (e.g. logical system name)

  • Why the command "ip device tracking" can't use in IA 15.2SY0a

    hello       i configure C6880 with VSS,and use C6800IA with IA,which version is 15.2SY0a,i found a question,when C6800IA run alone without IA uplink to C6880,the command "ip device tracking" can be found and use,but when C6800IA link to C6880 with IA

  • On a long two hour concert, 4 tracks aiff, is it possible to export to disk split track segments?

    Using Garageband 11 on a i3 iMac (2011), I downloaded a long contiguous symphony concert from a digital recorder as aif files. I split the tracks into segments to create separate songs to burn to CD Master. When I select a segment, then Share>Export