-1

I'm very confused how the imageIO works, I have this application:

enter image description here

I would like the save button to save all of its content in the JFrame as PNG. However it does not work, when I tried this code:

ImageIO.write(JFrame, "PNG", new File("filename.png"));

Any replies?

Pierre.Vriens
  • 2,117
  • 75
  • 29
  • 42
Petr Cina
  • 21
  • 8

2 Answers2

1

As per the JavaDocs, you need to pass ImageIO.write an instance of RenderedImage.

If you have a look at the JavaDocs for JFrame you will find that it doesn't implement RenderedImage, hence your problem.

If you have a look at just about any example of Image.write you'll find that almost always use a BufferedImage because it, unlike JFrame, does implement RenderedImage

Okay, so the question becomes, "how do I paint the JFrame to a BufferedImage?"

The answer, if you look around, is quite simple.

BufferedImage img = new BufferedImage(frame.getWidth(), frame.getHeight(), BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = img.createGraphics();
frame.printAll(g2d);
g2d.dispose();

And now, you can save it...

ImageIO.write(img, "png", new File("filename.png"));
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • Will I add the bufferedImage code to the save button or to the entire JFrame? – Petr Cina May 17 '17 at 08:26
  • That depends on when you want to save the image – MadProgrammer May 17 '17 at 08:26
  • I want to save the image on click of the save button, could you tell me where do I put the code? – Petr Cina May 17 '17 at 08:30
  • Put the code where you need to use. There's no point taking a snapshot of the frame before you want to save it – MadProgrammer May 17 '17 at 08:31
  • @MadProgrammer, finally see a concrete reason for using printAll() over paint(). (The double buffer doesn't seem to be an issue in that performance is still the same). On Windows, when using paint() the frame titlebar and border are just black. Using printAll() I do get a titlebar and border, however, it looks more like the Metal titlebar and border instead of the Windows LAF. So, on Windows at least, it still looks like the only way to get an image of the proper titllebar and border is to use the Robot. – camickr May 17 '17 at 14:38
  • @camickr I've also had issues with components which haven't been realised causing NPE when using paint and been black because of the double buffering, besides I think the op would prefer to capture the content pane and not the frame itself, but what do I know – MadProgrammer May 17 '17 at 19:59
0

Check out the Screen Image class.

It provides overloaded methods to paint components or a part of a component. The logic will then use either:

  1. The Robot class to paint a frame, or
  2. Swing painting to paint Swing components. (painting is more efficient than using the Robot).
camickr
  • 321,443
  • 19
  • 166
  • 288