Created
April 18, 2014 08:49
-
-
Save AdoPi/11032315 to your computer and use it in GitHub Desktop.
Save JPanel as image
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
Well done! Helps a lot!
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
is there a way to save the jpanel without showing it first?
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
Its working. Hurray!!!