Aaron said:
Hi,
If I drew a bunch of stuff to a JPanel, can I obtain the contents as a
BufferedImage?
Many thanks in advance,
Aaron
If your drawing code is all in the paintComponent() method (where it
should be), you can create a BufferedImage and call paintComponent()
with the Graphics object you get from the BufferedImage. If it isn't,
create the image before you draw to your JPanel and draw to both at the
same time.
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
import javax.swing.*;
public class test extends JPanel {
public test() {
setPreferredSize(new Dimension(400,300));
}
public void paintComponent(Graphics g) {
g.setColor(Color.WHITE);
g.fillRect(0,0,getWidth(),getHeight());
g.setColor(Color.GREEN);
g.drawLine(0,0,getWidth(),getHeight());
g.drawLine(getWidth(),0,0,getHeight());
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final test t = new test();
f.add(t,BorderLayout.CENTER);
JButton b = new JButton("Save Image");
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
BufferedImage bi = new BufferedImage(
t.getWidth(),t.getHeight(),
BufferedImage.TYPE_INT_RGB);
Graphics2D g = bi.createGraphics();
t.paintComponent(g);
try {
ImageIO.write(bi,"JPEG",
new File("image.jpg"));
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
});
f.add(b,BorderLayout.SOUTH);
f.pack();
f.setVisible(true);
}
});
}
}