1

我创建了一个函数,可以在其中单击 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;
    }
   /////////////////////////////////////////////////////////////////////    

}
4

1 回答 1

3

像这样保持一个ArrayListof Points:

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();
}
于 2012-11-25T08:49:06.843 回答