我正在嘗試構建一個西蒙說遊戲,它將閃爍按鈕按下。我目前正試圖弄清楚如何使按鈕一個接一個閃爍。遵循文檔(盡我所能),我編寫了下面的代碼,但出於某種原因,只有綠色按鈕閃爍。我進一步測試了一下,發現只有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