I have a JPanel upon which I draw a number of custom-written JComponents using the usual 'paintComponent(Graphics g)' method. I use a JLayeredPane to control the display order of the custom components, as follows:
public Class MyPanel extends JPanel {
private JLayeredPane layeredPane = new JLayeredPane();
private JComponent component1;
private JComponent component2;
public MyPanel() {
super();
setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
component1 = new CustomComponent1();
layeredPane.add (component1, new Integer(0));
component2 = new CustomComponent2();
layeredPane.add (component2, new Integer(1));
add (layeredPane);
}
public void resizePanel(Graphics g, int newWidth, int newHeight) {
component1.setBounds (f(x), f(y), f(newWidth), f(newHeight));
component2.setBounds (f(x), f(y), f(newWidth), f(newHeight));
}
public void paintComponent(Graphics g) {
if ((getWidth() != oldWidth) || (getHeight() != oldHeight)) {
oldWidth = getWidth();
oldHeight = getHeight();
resizePanel (g, getWidth(), getHeight());
}
super.paintComponent(g);
}
Now, I would like to export this panel to a JPEG file, but with a different size. When I use the following code, it successfully creates/exports a JPEG file of the desired size, but it also updates my screen image version of the panel to the new size! Yikes!
public void export(File file, int width, int height)
throws IOException
{
BufferedImage scaledImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = scaledImage.createGraphics();
resizePanel (g2, width, height);
super.paintComponent (g2);
try {
OutputStream out = new FileOutputStream(file);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(scaledImage);
out.close();
} catch (FileNotFoundException e) {
throw new IOException ("Unable to export chart to ("
+ file.getAbsolutePath() + "): " + e.getLocalizedMessage());
} finally {
g2.dispose();
}
}
How can I 'draw' an image suitable for exporting, but not actually cause this new image to be displayed?
Thanks!