2012-11-25 31 views
1

我已经创建了一个函数,我可以在哪里点击一个Jpanel中的某个地方,它在鼠标单击的位置绘制一个形状。我遇到的问题是当我点击一个新的位置时,它移动了形状并重新绘制了它。我希望以前的形状能够“烧”进屏幕并留在那里。它不需要绑定任何数据,我只是希望形状图像能够显示每次以前的位置。我尝试了很多不同的东西,但没有成功。这里是我的意思是:绘制一个形状,但保持在屏幕上的最前面的形状在java

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

你必须自己记住以前的形状。想法:'BufferedImage' –

回答

3

保持PointArrayList的人就像这样:

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(); 
}