在Java中打印60秒倒计时

时间:2014-03-14 22:31:10

标签: java jframe seconds

我在各处搜索了一些简单的代码,打印60秒,比如JFrame构造函数。因此,当运行JFrame时,窗口标题将显示为60-0秒的倒计时(在我的情况下将关闭)。 - 无需关闭代码。

有些内容:

JFrame frame = new JFrame("Window will terminate in: " + java.util.Calendar.SECOND);

当然上面的代码没有意义,因为它打印当前时间秒。但是你明白了。

3 个答案:

答案 0 :(得分:4)

只需创建一个Swing Timer并将计数器初始化为60。

设置每秒调用的计时器。

每次将计数减少一次并更新文本。

当你达到0时,不管你在倒计时结束时做什么,都要停止计时器。

答案 1 :(得分:3)

使用TimerTask每秒设置JFrame的标题。

public class TimerFrame {
    private static JFrame frame = new JFrame();

    public static void main(String[] args) {
        TimerFrame timerFrame = new TimerFrame();
        timerFrame.frame.setVisible(true);
        timerFrame.frame.setSize(400,100);
        new Timer().schedule(new TimerTask(){

            int second = 60;
            @Override
            public void run() {
                frame.setTitle("Application will close in " + second-- + " seconds.");
            }   
        },0, 1000);
    }
}

答案 2 :(得分:2)

试试这个:

int count = 60;
while(count != 0){
        try {
            countlabel.setText(String.valueOf(count));
            count--;
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }