我创建了一个函数,我可以在其中单击 Jpanel 中的某处,它会在鼠标单击的位置绘制一个形状。我遇到的问题是当我点击一个新位置时,它会移动形状并重新绘制它。我希望以前的形状“刻录”到屏幕上并留在那里。它不需要绑定(bind)任何数据,我只希望形状的图像每次都能显示它曾经所在的位置。我尝试了很多不同的事情,但没有成功。这就是我的意思:
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;
}
/////////////////////////////////////////////////////////////////////
}
最佳答案
像这样保存一个点
的ArrayList
:
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();
}
关于java - 在 java 中绘制一个形状但在屏幕上保留最新的形状,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13549506/