简体   繁体   English

用Java打印60秒倒计时

[英]Print 60 seconds countdown in Java

I've searched everywhere for some simple code to print 60 seconds down, say on a JFrame constructor. 我到处搜索了一些简单的代码来打印60秒,例如在JFrame构造函数上。 So when a JFrame is run, the window title will be shown a countdown from 60-0 seconds (which in my case will shutdown). 因此,当运行JFrame时,窗口标题将显示从60-0秒倒计时(在我的情况下将关闭)。 - No need for code to shutdown. -无需关闭代码。

Something on the lines of: 在以下方面:

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

Of course the code above does not make sense because it's printing the current time second. 当然,上面的代码没有意义,因为它以秒为单位打印当前时间。 But you get the idea. 但是你明白了。

Just create a Swing Timer and have a counter initialized at 60. 只需创建一个Swing计时器,并将计数器初始化为60。

Set up the timer to be called every second. 将计时器设置为每秒调用一次。

Each time reduce the count by one and update the text. 每次将计数减少一并更新文本。

When you reach 0 do whatever you do for the end of the countdown and stop the timer. 当您达到0时,请在倒数计时结束时做任何事情,然后停止计时器。

Use a TimerTask to set the title of the JFrame every second. 使用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);
    }
}

Try this: 尝试这个:

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();
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM