尝试将自定义Java JPanel导出到PNG文件时出现了一个有趣的问题。到目前为止,我一直在撰写的组件的出口过程完美无瑕。嵌入式Swing组件未定位在导出图像中的自定义JComponent
我的JPanels包含自定义编写的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();
}
}
的'画()方法将导致所有的JPanel的子组件的使用新的重新绘制要导出图像的大小。工作得很好。
我今天遇到的问题是我有一个自定义JPanel,它包含一些Swing组件(一个包装JEditorPane的JScrollPane)。这个JPanel包含我的一个自定义JComponents,然后是第二个带有JScrollPane的JComponent。
大约75%的时间,当我执行导出时,带有JScrollPane的第二个JComponent未在导出的图像中正确定位。它位于Point(0,0)处,大小与它在屏幕上的样子相同。对于此JComponent的'画()方法如下所示:
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% - 此模型上具有ScrollPane正确定位在我的导出图像。重新绘制组件作品。
好像是有一些双缓冲会在这里,我不能figger出来....
想法?
不,我不知道。自定义的JComponents刚刚绘制在新图像的图形上下文中。他们使用传入的矩形做了(做)所有的低位定位。 – redBeard 2010-08-26 21:37:56