如何在Java中使倒计时器?

时间:2016-05-30 04:02:17

标签: java timer label

我想每秒倒计时并更新标签文字?

int countdown = 100;

public void countingDown() {
    countdown = countdown - 1;
    label.setText(countdown + "second's left");
}

那么如何每秒运行countingDown

3 个答案:

答案 0 :(得分:1)

你可能会这样:

package com.example;

import java.util.Timer;
import java.util.TimerTask;

public class MyTimer {

    public static void main(String[] args) {
        Timer timer = new Timer();
        timer.schedule(new App(), 0, 1000);
    }
}

class App extends TimerTask {

    int countdown = 100;

    public void run() {
        countdown = countdown - 1;
        System.out.println(countdown);
        //label.setText(countdown +"second's left");
    }

}

// Result:
//99
//98
//97
//96
//95
//94

它只是有效。根据您的需要,将System.out.println(countdown);改为label.setText(countdown +"second's left");

参考
http://docs.oracle.com/javase/8/docs/api/index.html?java/util/TimerTask.html
http://docs.oracle.com/javase/8/docs/api/index.html?java/util/Timer.html

答案 1 :(得分:0)

您可以使用以下代码

final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
        final Runnable refresh = new Runnable() {
            public void run() {
                //countingDown stuff;
            }
        };
scheduler.scheduleAtFixedRate(refresh, 0, 1,SECONDS);

答案 2 :(得分:-1)

试试这个

int countdown=100;

    public void countingDown(){

     new Timer().schedule(new TimerTask(){

            @Override
            public void run() {
             countdown=countdown - 1;

                label.setText(countdown +"second's left");
            }   
        },0, 1000);
    }