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);
}
}
@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