saving a onscreen component to image file

I have a custom JPanel with the paintComponent() overridden to draw something custom. To export it to an image file, I drew the component into another graphics object.


JPanel custom = ...;
BufferedImage image = new BufferedImage(...);
custom.paint(image.getGraphics());

After this the image would have contained what it looks like on screen. The next step is straightforward: save the image:

ImageIO.write(image, "png", file);

Additional tip: Knowing how Swing render lightweight components is very useful.

Leave a Reply