【问题标题】:Creating a count down timer- Java创建倒数计时器 - Java
【发布时间】:2015-11-13 14:54:29
【问题描述】:
    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。

【问题讨论】:

    标签: java timer countdown countdowntimer netbeans-8


    【解决方案1】:

    您的计时器每次运行时,都会执行从 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,你应该取消你的时间,否则它仍然会每秒运行,但没有实际效果或需要。

    【讨论】:

    • 很抱歉打扰您,我不知道我是否可以再问一个问题,但是如何重置计时器?
    【解决方案2】:

    问题是,每次执行TimerTask,你直接数到30,所以每次都会数到30。您想要做的是将当前时间存储在 TimerTask 之外的 i 变量,并在每次 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);
            }
        }
    };
    

    【讨论】:

    • 好点,谢谢。为了完整起见,我在我的代码示例中修复了它。已经给出了另一个具有相同代码的答案。
    猜你喜欢
    • 2019-07-10
    • 2022-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多