创建倒数计时器 - Java [英] Creating a count down timer- Java

查看:28
本文介绍了创建倒数计时器 - 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆