我已经制作了一个代码来在JPanel
上绘制
frame1.add( new JPanel() {
public void paintComponent( Graphics g ) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.setColor(Color.white);
g2.fillRect(0, 0, width, height);
//Drawnig Part
});
JPanel
上绘制的内容保存在文件a. PNG
或任何其他类型Drawing Part
,所以如果你能通过更改我代码中所需的部分来提出解决方案,而不是重写整个代码,那将是很有帮助的。
我建议您使用BufferedImage缓冲绘图操作,如下所示:
// This should not be done in the draw method, but rather when
// the frame is created. You should also make a new buffer image when
// the frame is resized. `frameWidth` and `frameHeight` are the
// frame's dimensions.
BufferedImage bufferImage = new BufferedImage(frameWidth, frameHeight,
BufferedImage.TYPE_INT_ARGB);
Graphics2D bufferGraphics = bufferImage.createGraphics();
// In your draw method, do the following steps:
// 1. Clear the buffer:
bufferGraphics.clearRect(0, 0, width, height);
// 2. Draw things to bufferGraphics...
// 3. Copy the buffer:
g2.drawImage(bufferImage, null, 0, 0);
// When you want to save your image presented in the frame, call the following:
ImageIO.write(bufferImage, "png", new File("frameImage.png"));
如果您需要更多信息,有关创建和绘制图像的Java教程以及ImageIOAPI参考可能会有所帮助。
查看编写/保存图像以获取更多详细信息,但本质上您可以做类似的事情…
BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = img.createGraphics();
// Draw what ever you want to to the graphics context
g2d.dispose();
ImageIO.write(img, "png", new File("My Awesome Drawing.png"));
如果您无法将绘图逻辑与面板分开,您可以简单地使用BufferedImage
中的Graphics
上下文来绘制组件。
查看将JPanel导出到图像并打印整个程序布局的示例