I want to capture the contents of a JPanel as an image so that I can store it exactly as the user sees it. Is there a relatively simple way to do this with swing?
From here http://forums.oracle.com/forums/thread.jspa?threadID=2156176&tstart=0
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class SavePaint extends JPanel
{
public SavePaint()
{
JFrame frame = new JFrame("TheFrame");
frame.add(this);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400,400);
frame.setVisible(true);
try
{
BufferedImage image = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB);
Graphics2D graphics2D = image.createGraphics();
frame.paint(graphics2D);
ImageIO.write(image,"jpeg", new File("/home/deniz/Desktop/jmemPractice.jpeg"));
}
catch(Exception exception)
{
//code
}
}
protected void paintComponent(Graphics g)
{
g.drawRect(50,50,50,50);
}
public static void main(String[] args)
{
new SavePaint();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With