本文介绍了创建倒计时器 - 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。

I have created a timer that starts when I press a button and above is the code that run. Can anyone help me create a timer that counts to 30? Right now when I run it, sets the text "30" in the label but I want it to start at 0 and count until 30.

推荐答案

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

Each time your timer runs, it performs the loop from 0 to 30, thus the UI is refreshed only when the loop ends. You need to keep your i in a member and update it each time the run method is called as such:

    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时,你应该取消你的时间,否则它仍会每秒运行但没有真正的效果或需要。

Of course once your reach i = 30, you should cancel your times, otherwise it'll still run every second but with no real effect or need.

这篇关于创建倒计时器 - Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 06:29