This is about taking a screenshot of a JPanel to save the visible stuff as an image to disk.

Sometimes it may happen that you create a swing GUI with a panel to draw cool stuff. Here you can learn how to let the user take a screenshot of this graphic with a single click on a button.

First of all create such a JPanel and fill it with crazy graphics, then create a BufferedImage with the size of the panel and tell the panel to draw its content to this image instead of printing the content to the screen and, last but not least, save this image:

// create a panel
javax.swing.JPanel panel = new javax.swing.JPanel ();
// [..] tell the panel to look nice

// create an image
java.awt.image.BufferedImage bImage = new java.awt.image.BufferedImage (panel.getSize ().width, panel.getSize().height, java.awt.image.BufferedImage.TYPE_INT_RGB);
// tell the panel to draw its content to the new image
panel.paint (bImage.createGraphics ());
// save everything
{ imageFile = new ("/tmp/screener.png")
  imageFile.createNewFile ();  
  javax.imageio.ImageIO.write (bImage, "png", imageFile);  
catch(Exception ex)
  ex.printStackTrace ();

You see it’s very simple. Of course it’s also possible to create other types of image with ImageIO, like JPEG or GIF, but for more information take a look in the documentation. In a project that will be published you should think about using a JFileChooser instead of hard coding the name of the new image ;-)

Martin Scharm

stuff. just for the records.

Post a comment

read more about submitting comments