【发布时间】:2017-10-12 16:47:03
【问题描述】:
我目前正在尝试制作一个画布,我可以在其中绘制内容并将其显示在 JFrame 中。
为此,我打算在 JPanel 组件内有一个 BufferedImage,paintComponent 方法可以从中进行绘制。
理想情况下,我希望能够从给定的 JFrame 引用此缓冲图像,然后使用其 Graphics2D 向其绘制内容,然后在使用缓冲图像进行绘制时,paintComponent 方法可以显示这些内容。
我这样做是为了避免直接使用paintcomponent 方法,我希望能够从程序中的任何位置引用此画布,并在调用frame repaint() 方法时对其进行绘制。
class MyPanel extends JPanel {
BufferedImage img = new BufferedImage(500, 500, BufferedImage.TYPE_INT_ARGB);
Graphics2D imgG2 = img.createGraphics();
public Graphics2D getGraphics() {
return imgG2;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
int w = img.getWidth();
int h = img.getHeight();
g2.drawImage(img, 0, 0, w, h, null);
}
}
class Main {
private static JFrame createAndShowGui() {
JFrame frame = new JFrame("droneFrame");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.add(new MyPanel());
frame.setSize(500, 500);
frame.setResizable(false);
frame.setVisible(true);
return frame;
}
public static void main(String args[]) {
JFrame frame = createAndShowGui();
//Something here to reference the inner Jpanels imgG2 field, and draw to it.
frame.repaint();
//Draw whatever is currently in the buffered image.
}
}
但是,我不知道该怎么做,因为 frame.getComponent(0) 只返回一个组件,而不是它的特定类型的组件。
提前致谢。
【问题讨论】:
-
“理想情况下,我希望能够从给定的 JFrame 中引用这个缓冲图像” - 我认为这不是一个想法,原因有很多; 1-它正在耦合您的代码; 2- 它可能会导致图形故障,具体取决于您更新图像的方式,因为您可能会在组件绘制图像时更新图像
-
一个更好的解决方案可能是有一个类,它的唯一工作就是从某个来源获取输入,更新图像并生成某种“更新”通知,渲染引擎(即您的
JPanel) 可以收听然后重新绘制提供的图像。这将允许实现诸如页面翻转之类的事情以及流程的解耦,允许您以任何您想要的方式修改管道链中的任何链接,而不会影响其他链接
标签: java swing canvas jframe jpanel