Java 2D游戏:重画

时间:2018-05-05 13:21:36

标签: java swing

我正在为我的作业创建一个非常简单的游戏,现在我正在解决以下问题:

click shape上的mouseClicked(现在它只是一个圆圈),它应该消失并在其他地方渲染一个新的(当你击中那些形状时,你正在收集点数,这就是问题,我认为我的问题在于System.out.println()方法。我在那里设置了一些控件swing,每当程序到达此方法时,它会显示与圆圈一样多的打印件。我的意思是,如果你点击第一个圆圈它会显示一个打印,如果你点击第二个圆圈,它会显示两个打印,依此类推。你能帮帮我吗?我刚开始使用awtpublic 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"); } } } ,我没有太多时间进行彻底的学习。非常感谢你。

sample.sh
hadoop fs -touchz /user/123/test.txt

1 个答案:

答案 0 :(得分:1)

这种情况发生了,因为每次调用paintComponent时都会添加一个新的鼠标侦听器。你应该在构造函数中执行一次。

相关问题