我在尝试将自定义 Java JPanel 导出到 PNG 文件时遇到了一个有趣的问题。到目前为止,我一直在编写的组件的导出过程完美无缺。
我的 JPanel 包括自定义编写的 JComponents(例如,覆盖 paintComponent(Graphics g) 并写下我必须写的东西)。
导出过程如下所示(我拥有的扩展 JPanel):
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();
}
}
上面的 'draw()' 方法导致使用要导出的图像的新大小重新绘制 JPanel 的所有子组件。效果很好。
我今天遇到的问题是我有一个自定义 JPanel,其中包含一些 Swing 组件(一个 JScrollPane 包装了一个 JEditorPane)。这个 JPanel 包括我的一个自定义 JComponent,然后是第二个 JComponent,上面有 JScrollPane。
大约 75% 的时间,当我执行导出时,带有 JScrollPane 的第二个 JComponent 没有正确定位在导出的图像中。它位于 Point (0, 0) 处,大小就是它在屏幕上的样子。此 JComponent 的“draw()”方法如下所示:
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);
}
但是大约有 25% 的时间可以正常工作 - 这个带有滚动窗格的 JComponent 正确定位在我导出的图像中。重新绘制组件作品。
就像这里发生了一些我无法弄清楚的双重缓冲......
想法?