尝试编写一个计时器来进行倒计时(就像火箭发射:3-2-1-Go)。我所拥有的似乎只执行一次。我需要它重复(几乎是递归地)执行直到值达到 0。
如您所见,我有各种 println 语句来跟踪此过程。这是我的输出:
in Coundown constructor
in ActionListener
counting down
3
错误的是我缺少以下输出:
2
1
Go
这向我表明这个计时器实际上并没有倒计时。它似乎在等待一秒钟然后终止。
我怎样才能让它在计时器达到零之前调用自己?谢谢!
public class StopWatch {
JFrameMath myTest;
int seconds;
/* Constructor */
public StopWatch(JFrameMath thisTest, int sec) {
myTest = thisTest;
seconds = sec;
myTest.hideTestButtons(true);
Countdown display = new Countdown(myTest);
}
}
class Countdown extends JFrame implements ActionListener {
private Timer myTimer = new Timer(250, this);
JFrameMath myTest;
public Countdown(JFrameMath thisTest) {
System.out.println("in Coundown constructor");
myTimer.setInitialDelay(1150);
myTest = thisTest;
myTimer.start();
}
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("in ActionListener");
int countSeconds = 3;
if(countSeconds == 0) {
myTest.showTimeRemaining("Go");
myTimer.stop();
System.out.println("done");
} else {
System.out.println("counting down");
myTest.showTimeRemaining(""+countSeconds);
countSeconds--;
}
myTimer.stop();
myTest.hideTestButtons(false);
}
}
public void showTimeRemaining(JFrameMath thisTest, String numSec) {
System.out.println(numSec);
lblCountdown.setText(numSec);
thisTest.pack();
}
最佳答案
从 actionPerformed
的末尾删除 myTimer.stop()
。这就是阻止它触发后续事件的原因。唯一要调用 stop
的地方是 if (countSeconds == 0)
。
此外,我不知道这是错字还是测试,但您需要从 actionPerformed
中删除行 int countSeconds = 3;
。
关于java - 使用计时器倒计时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12022780/