创建倒数计时器- Java

Creating a count down timer- Java

    Timer timer = new Timer();

    TimerTask task = new TimerTask(){
        public void run(){
            for (int i = 0; i <= 30; i++){
                lblTimer.setText("" + i);
            }
        }
    };
    timer.scheduleAtFixedRate(task, 0, 1000); //1000ms = 1sec

我创建了一个计时器,当我按下按钮时它会启动,上面是 运行 的代码。谁能帮我制作一个数到 30 的计时器?现在,当我 运行 它时,在标签中设置文本“30”,但我希望它从 0 开始计数直到 30。

每次你的定时器运行s,它执行从0到30的循环,因此UI只有在循环结束时才会刷新。您需要将 i 保留在成员中并在每次调用 run 方法时更新它:

    Timer timer = new Timer();

    TimerTask task = new TimerTask(){
        private int i = 0;
        public void run(){
            if (i <= 30) {
                lblTimer.setText("" + i++);
            }
        }
    };
    timer.scheduleAtFixedRate(task, 0, 1000); //1000ms = 1sec

当然,一旦你达到 i = 30,你应该取消你的时间,否则它仍然会每秒 运行 但没有实际效果或需要。

问题是每次TimerTask执行的时候直接数到30,所以每次都会数到30。您想要做的是让 i 变量将当前时间存储在 TimerTask 之外,并在每次执行 TimerTask 时将其递增 1。

这看起来像这样:

TimerTask task = new TimerTask(){

    // initially set currentTime to 0
    int currentTime = 0;

    public void run(){

        // only increment if currentTime is not yet 30, you could also stop the timer when 30 is reached
        if (currentTime < 30) {

            // increment currentTime by 1 and update the label
            currentTime++;
            lblTimer.setText("" + i);
        }
    }
};