1

I've made a code to draw on a Jpanel

frame1.add( new JPanel() {
    public void paintComponent( Graphics g ) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D)g;
        g2.setColor(Color.white);
        g2.fillRect(0, 0, width, height);
        //Drawnig Part
});
  • Every thing is OK
  • Now My question is how to save what I've drawn on my JPanel in a file a.PNG or any other type
  • I have spent a lot of time to write the Drawing Part, So it will be helpful if you can suggest a solution by changing the required parts of my code, instead of rewriting the whole code.
Karthik
  • 4,950
  • 6
  • 35
  • 65

2 Answers2

1

I suggest that you buffer your drawing operations with a BufferedImage, like so:

// This should not be done in the draw method, but rather when
// the frame is created. You should also make a new buffer image when
// the frame is resized. `frameWidth` and `frameHeight` are the
// frame's dimensions.
BufferedImage bufferImage = new BufferedImage(frameWidth, frameHeight,
            BufferedImage.TYPE_INT_ARGB);
Graphics2D bufferGraphics = bufferImage.createGraphics();


// In your draw method, do the following steps:

// 1. Clear the buffer:
bufferGraphics.clearRect(0, 0, width, height);

// 2. Draw things to bufferGraphics...

// 3. Copy the buffer:
g2.drawImage(bufferImage, null, 0, 0);

// When you want to save your image presented in the frame, call the following:
ImageIO.write(bufferImage, "png", new File("frameImage.png"));

The Java Tutorial on Creating and Drawing to an Image, along with the ImageIO API reference might be helpful should you require more information.

Ben Barkay
  • 5,473
  • 2
  • 20
  • 29
0

Have a look at Writing/Saving an Image for more details, but essentially you can do something like...

BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = img.createGraphics();
// Draw what ever you want to to the graphics context
g2d.dispose();

ImageIO.write(img, "png", new File("My Awesome Drawing.png"));

If you can't separate the drawing logic from your panel, you could simply use the Graphics context from the BufferedImage to paint the the component with.

Have a look at Exporting a JPanel to an image and Print the whole program layout for examples

Community
  • 1
  • 1
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366