java - 使用计时器倒计时

标签 java swing timer

尝试编写一个计时器来进行倒计时(就像火箭发射: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/

相关文章:

Java - 处理文件删除

java - 从自定义 DialogPreference 中检索值并保存值

java - 在 hibernate 中制作示例程序

java - 我如何根据输入到数字字段中的数字在切换按钮上设置延迟?

java - 如何直接从 Git 生成 javadoc

java - 如何使 JTable 的宽度 >= 封闭滚动 Pane 的宽度?

java - 如何调整 GridLayout 中 JComponent 的大小?

Java 二十一点 Swing gui ImageIcon

objective-c - 计划任务以在 iOS 中执行方法

timer - Ratchet WampServerInterface 和计时器