用 Java 打印 60 秒倒计时

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22416939/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 15:37:01  来源:igfitidea点击:

Print 60 seconds countdown in Java

javajframeseconds

提问by Douglas Grealis

I've searched everywhere for some simple code to print 60 seconds down, say on a JFrame constructor. So when a JFrame is run, the window title will be shown a countdown from 60-0 seconds (which in my case will shutdown). - No need for code to shutdown.

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

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.

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

采纳答案by Kevin Bowersox

Use a TimerTaskto set the title of the JFrameevery second.

使用 aTimerTask设置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);
    }
}

回答by Tim B

Just create a Swing Timerand have a counter initialized at 60.

只需创建一个Swing Timer并将计数器初始化为 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 时,请在倒计时结束时执行任何操作并停止计时器。

回答by Salah

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