Skip to content

Instantly share code, notes, and snippets.

@AdoPi
Created April 18, 2014 08:49
Show Gist options
  • Save AdoPi/11032315 to your computer and use it in GitHub Desktop.
Save AdoPi/11032315 to your computer and use it in GitHub Desktop.
Save JPanel as image
import java.awt.*;
import javax.swing.*;
import java.io.*;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
public class Panel extends JPanel {
/**
* Save the Panel as image with the name and the type in parameters
*
* @param name name of the file
* @param type type of the file
*/
public void saveImage(String name,String type) {
BufferedImage image = new BufferedImage(getWidth(),getHeight(), BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = image.createGraphics();
paint(g2);
try{
ImageIO.write(image, type, new File(name+"."+type));
} catch (Exception e) {
e.printStackTrace();
}
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
}
}
@HasaanAli
Copy link

Its working. Hurray!!!

@jerrylususu
Copy link

Well done! Helps a lot!

@RustyKnight
Copy link

You should never call paint directly. If the component is not realised on the screen, this could trigger an exception to be generated. Better to use printAll

@schw-rtz
Copy link

is there a way to save the jpanel without showing it first?

@RustyKnight
Copy link

Use printAll instead if paint, but also, make sure you size it using getPreferredSize

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment