I have a funny problem trying to export custom Java JPanels to a PNG file. The export process of the components I've been writing up until now have worked flawlessly.
My JPanels include custom-written JComponents (e.g., override paintComponent(Graphics g) and write what I have to).
The export process looks like the following (of the extended JPanel I have):
public void export(File file, int width, int height)
throws IOException
{
Dimension size = getSize();
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = image.createGraphics();
draw (g2, new Rectangle (0, 0, width, height));
try {
ImageIO.write(image, "png", file);
} catch (FileNotFoundException e) {
throw new IOException ("Unable to export chart to ("
+ file.getAbsolutePath() + "): " + e.getLocalizedMessage());
} finally {
g2.dispose();
}
}
The 'draw()' method above causes all of the JPanel's child components to be re-drawn using the new size of the image to be exported. Works very well.
The problem I have today is that I have one custom JPanel that includes some Swing components (a JScrollPane wrapping a JEditorPane). This JPanel includes one of my custom JComponents and then this second JComponent with the JScrollPane on it.
About 75% of the time, this second JComponent with the JScrollPane is not positioned correctly in the exported image when I perform the export. It is positioned at Point (0, 0) and the size is what it looks like on the screen. The 'draw()' method for this JComponent looks like the following:
public void draw(Graphics2D g2, Rectangle componentArea) {
scrollPane.setBounds(componentArea);
textArea.setText(null);
sb.append("<html>");
sb.append("<h1 style=\"text-align:center;\">" + "XXXXXXXXX XXXXXXX" + "</h1>");
textArea.setText(sb.toString());
super.paintComponents(g2);
}
But about 25% of the time this works - this JComponent with the scrollpane is correctly positioned in my exported image. The re-draw the componment works.
It is like there is some double-buffering going on here that I can't figger out....
Ideas?