更新Java Canvas中的绘图

Mav*_*rik 0 java swing awt

我想创建一个可以在画布上绘制路径的应用程序.问题是我必须不断更新这个画布.

目前我能够做到,但我必须每次重绘所有路径,所以我必须将所有点存储在内存中.我更愿意通过添加新点来简单地更新绘图.

可能吗?

目前我的代码是:

public class MyCanvas extends Canvas{
        private static final long serialVersionUID = 1L;
        public MyCanvas(){}
        public void paint(Graphics graphics){
            super.paint(graphics);
            graphics.setColor(Color.green);
            // points is an ArrayList of Point2D
            for (Iterator iterator = points.iterator(); iterator.hasNext();) {
               Point2D point2d = (Point2D) iterator.next();
               graphics.fillOval((int)((canvas.getWidth()/2.0) + point2d.getX()), (int)((canvas.getHeight()/2.0) + point2d.getY()), 5, 5);
            }   
        }
    }
Run Code Online (Sandbox Code Playgroud)

谢谢!

编辑

这是目前的解决方案:

PanelCanvas canvasPanel;
...
public void drawCircle(int x, int y){
    Graphics2D g2d = bufferedImage.createGraphics();
    g2d.setColor(Color.green);
    g2d.setBackground(Color.white);
    g2d.fillOval((int)((panelCanvas.getWidth() / 2.0) + x/10.0), (int)((panelCanvas.getHeight() / 2.0) + y/10.0), 5, 5);
    panelCanvas.repaint();
}

public class CanvasPanel extends JPanel{
    public void paintComponent(Graphics graphics){
        super.paintComponents(graphics);
        Graphics2D g2d = (Graphics2D)graphics;
        g2d.setBackground(Color.white);
        g2d.drawImage(bufferedImage, null, 0, 0);
    }
}
Run Code Online (Sandbox Code Playgroud)

And*_*son 5

绘制点(无论如何)到a BufferedImage.期间paint(),画画BufferedImage.


但请注意,JRE可以在绘制中绘制数千个对象,而不会产生任何视觉伪像或减速.


画布嵌入在Swing GUI中.你有什么建议替换AWT.Canvas?

JComponent用于完整自定义渲染,JPanel用于与组件结合的自定义渲染.这听起来像是JComponent更适合这个用例.

对于其中任何一个,覆盖paintComponent(Graphics)而不是paint(Graphics).其余的建议是一样的.