如何通过JPanel
类型(即extends
/从JPanel
继承的自定义类)将每个重绘调用(直接或非直接)写入{{1 }
在自定义类中做这种事情' BufferedImage
不起作用:
paintComponent
结果protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D G2 = (Graphics2D) g;
// ... draw objects
BufferedImage imageBuffer = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB);
G2 = imageBuffer.createGraphics();
// Which doesn't work, because with that method it seems you would
// need to call paint() on Graphics2D reference here.
// And to do so would then throw an Illegal Exception.
}
是调用BufferedImage
的{{1}}类型类的正确大小,但是图像是黑色的(即空的) - 这完全是逻辑的,因为{{1}单独不做任何事。
我知道Rob Camick的ScreenImage代码 - 但这似乎只适用于程序初始化时的单个屏幕截图。
让我感到困惑的是,JPanel
在显示在屏幕上之前必须保留在内存中...所以有没有办法每次都抓住它并将其保存到paintComponent
?
答案 0 :(得分:1)
这种方法怎么样?与您发布的代码的不同之处在于,您需要在BufferedImage
上完成所有自定义绘图。然后你只在组件上绘制一个东西:BufferedImage
。
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
BufferedImage imageBuffer = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB);
Graphics imageG2 = imageBuffer.createGraphics();
// do custom painting onto imageG2...
// save imageBuffer
g2.drawImage(imageBuffer, 0, 0, this); // draw onto component
}
答案 1 :(得分:1)
描述和一些细节可能不完全清楚。但它基本上听起来像是要创建一个可以像普通JPanel
一样使用的组件,但paintComponent
方法中绘制的所有内容也应保存为BufferedImage
。< / p>
对此有不同的解决方案。您可以拨打专用电话,例如
myComponent.paintComponent(bufferedImageGraphics);
并相应地处理图像,如一个答案中所提出的。另一个答案建议创建一个自定义paintComponent
方法来执行图像处理。
但是,我想提出以下解决方案:您可以创建一个扩展ImageSavingComponent
的{{1}}类。在本课程中,您不能覆盖JPanel
方法,而是覆盖paintComponent
方法。 paint
方法做了两件事:
paint
,绘制成图像super.paint(bufferedImageGraphics)
,画在屏幕上这样,您可以简单地扩展此类,并像对待任何super.paint(componentGraphics)
一样实施paintComponent
方法。图像处理可以完全透明地完成。
在下面的示例中,我添加了一个JPanel
接口,用于接收图像并对其进行适当处理。如果Consumer
为Consumer
,则不会生成任何图片。为了测试,我创建了一个这个接口的实现,它只是每200ms将图像存储在文件中。 (如果需要,可以用Java 8 null
接口替换此接口)
Consumer
答案 2 :(得分:0)
您必须在组件的paint函数之外创建BufferedImage
,然后使用BufferedImage
图形作为参数调用此paint函数。
BufferedImage imageBuffer = new BufferedImage(comp.getWidth(), cmp.getHeight(), BufferedImage.TYPE_INT_RGB);
cmp.paint(imageBuffer.getGraphics());