我正在尝试构建一个西蒙说游戏,它将闪烁按钮按下。我目前正试图弄清楚如何使按钮一个接一个闪烁。遵循文档(尽我所能),我编写了下面的代码,但出于某种原因,只有绿色按钮闪烁。我进一步测试了一下,发现只有btnGo
事件中的最后一种方法才能正常工作。我认为这与计时器的运行方式有关,它在计时器结束之前将红色和蓝色按钮变回黑色,但我不确定如何或为什么?摆动定时器仅在最后一个事件上运行
public void flashRed(){
btn1.setBackground(Color.red);
btn2.setBackground(Color.black);
btn3.setBackground(Color.black);
btn4.setBackground(Color.black);
repaint();
t.start();
}
public void flashYellow(){
btn1.setBackground(Color.black);
btn2.setBackground(Color.yellow);
btn3.setBackground(Color.black);
btn4.setBackground(Color.black);
repaint();
t.start();
}
public void flashGreen(){
btn1.setBackground(Color.black);
btn2.setBackground(Color.black);
btn3.setBackground(Color.green);
btn4.setBackground(Color.black);
repaint();
t.start();
}
public void flashBlue(){
btn1.setBackground(Color.black);
btn2.setBackground(Color.black);
btn3.setBackground(Color.black);
btn4.setBackground(Color.blue);
repaint();
t.start();
}
@Override
public void actionPerformed(ActionEvent event) {
if(event.getSource() == btnGo)
{
flashRed();
flashBlue();
flashGreen();
}
if(event.getSource() ==t){
btn1.setBackground(Color.black); //resets btn1 to black
btn2.setBackground(Color.black);
btn3.setBackground(Color.black);
btn4.setBackground(Color.black);
repaint();
t.stop(); //stops the timer
}
}
(event.getSource()== t)是不正确的使用.equals代替 – 2014-10-18 14:07:53
你需要在每次调用之间使用Thread.sleep – subash 2014-10-18 14:32:50
@getlost如果将'ActionListener'附加到'Timer',则源代码将与您连接侦听器的实例完全相同,因此使用'=='是完全有效的代码。不需要使用“equals”。 @subash在他的代码中,我只检测EDT的用法。除非您正在设计无响应的用户界面,否则永远不要在EDT上调用Thread.sleep。 – Robin 2014-10-18 15:18:14