swing Java 2D游戏:重绘
我正在为我的家庭作业制作一个非常简单的游戏,现在我正在解决以下问题:
在这个游戏中,当你在shape
上click
时(现在它只是一个圆),它应该消失,并在其他地方渲染一个新的(当你击中那个形状时,你正在收集点,这就是点),我想我的问题是mouseClicked
方法。我在那里放置了一些控件System.out.println()
,每次程序达到这个方法时,它都会显示与圆圈一样多的打印。我的意思是,如果你点击第一个圆圈,它会显示一个打印,如果你点击第二个圆圈,它会显示两个打印,依此类推。你能帮我吗?我刚从{
public class Shape extends JPanel implements ActionListener{
Graphics2D g2;
Ellipse2D circle;
Timer t = new Timer(2000, this);
int x, y, count;
JLabel counting;
public Shape(JLabel counting){
this.counting = counting;
}
public void paintComponent(Graphics g){
super.paintComponent(g);
g2 = (Graphics2D)g;
ListenForMouse lForMouse = new ListenForMouse();
addMouseListener(lForMouse);
Random ran = new Random();
int green = ran.nextInt(256);
int red = ran.nextInt(256);
int blue = ran.nextInt(256);
Color randomColor = new Color(green, red, blue);
int wid = ran.nextInt(101) + 50;
x = ran.nextInt(650);
if(x > wid)
x = x - wid;
y = ran.nextInt(600);
if(y > wid)
y = y - wid;
circle = new Ellipse2D.Double(x,y,wid,wid);
t.start();
g2.setColor(randomColor);
g2.fill(circle);
}
@Override
public void actionPerformed(ActionEvent arg0) {
repaint();
}
private class ListenForMouse implements MouseListener{
@Override
public void mouseClicked(MouseEvent e) {
System.out.println("Control before");
if(circle.contains(e.getPoint())){
count++;
counting.setText(Integer.toString(count));
t.stop();
repaint();
System.out.println("Control in");
}
System.out.println("Control out");
}
}
}
# 1 楼答案
这种情况会发生,因为每次调用
paintComponent
时都会添加一个新的鼠标侦听器。您应该在构造函数中执行一次