绘制一个形状,但在java中保持屏幕上最先前的形状

时间:2012-11-25 08:37:41

标签: java drawing paint shapes

我创建了一个函数,我可以在Jpanel中的某个位置单击它,并在鼠标单击的位置绘制一个形状。我遇到的问题是当我点击一个新位置时,它会移动形状并重新绘制它。我希望以前的形状“刻录”到屏幕上并留在那里。它没有任何数据与它相关联,我只想让形状的图像显示每次的位置。我尝试了很多不同的东西,但没有成功。这就是我的意思:

public void paintComponent(Graphics g) {

    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D) g;
    g2.setColor(Color.BLUE);
    g2.fillRect(n, m, 32, 32); //I want each one of these shapes to be new, not
                                       //moving, but redrawn      

    ////////////////////////////////////////////////
    //This is just drawing a grid and doing other things(irrelevant)
    g2.fill(new Ellipse2D.Double(x, y, 32, 32));
    for (int i = 0; i < 500; i += 32) {
        g2.drawRect(i, j, 32, 32);
        for (int j = 0; j < 500; j += 32) {
            g2.drawRect(i, j, 32, 32);
        }
    }


    if (paintColBlock){
        System.out.println("Drawing Block at " + n +"," + m);
        paintColBlock = false;
    }
   /////////////////////////////////////////////////////////////////////    

}

1 个答案:

答案 0 :(得分:3)

保留ArrayList Point这样的内容:

public void paintComponent(Graphics g) {

super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.BLUE);
for(Point p : points)
    g2.fillRect(p.x, p.y, 32, 32);

每次点击鼠标时向数组添加新Point,然后致电repaint()

public void mousePressed(MouseEvent evt){
    points.add(new Point(evt.getX(),evt.getY());
    repaint();
}