每秒更新 GUI 的 Java 秒表?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11058172/
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-10-31 03:37:34  来源:igfitidea点击:

Java Stopwatch that updates the GUI every second?

javaswinguser-interfacestopwatch

提问by Dangerosking

I'm a Java beginner and I'm trying to build a simple stopwatch program that displays the time on a swing GUI. Making the stopwatch is easy, however I cannot find a way to make the GUI update every second and display the current time on the stopwatch. How can I do this?

我是一名 Java 初学者,我正在尝试构建一个简单的秒表程序,在摆动 GUI 上显示时间。制作秒表很容易,但是我找不到让 GUI 每秒更新一次并在秒表上显示当前时间的方法。我怎样才能做到这一点?

回答by GETah

Something along these lines should do it:

应该这样做:

import java.awt.EventQueue;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JFrame;
import javax.swing.JLabel;

/** @see https://stackoverflow.com/a/11058263/230513 */
public class Clock {

    private Timer timer = new Timer();
    private JLabel timeLabel = new JLabel(" ", JLabel.CENTER);

    public Clock() {
        JFrame f = new JFrame("Seconds");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(timeLabel);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
        timer.schedule(new UpdateUITask(), 0, 1000);
    }

    private class UpdateUITask extends TimerTask {

        int nSeconds = 0;

        @Override
        public void run() {
            EventQueue.invokeLater(new Runnable() {

                @Override
                public void run() {
                    timeLabel.setText(String.valueOf(nSeconds++));
                }
            });
        }
    }

    public static void main(String args[]) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                final Clock clock = new Clock();
            }
        });
    }
}

The timeLabelwill always display the number of seconds the timer has been running.

timeLabel会始终显示计时器已经运行的秒数。

  1. You will need to correctly format it to display "hh:mm:ss"; one approach is shown here.

  2. Create a container and add the label to it so that you can display it as part of the GUI.

  3. Compare the result to this alternateusing javax.swing.Timer.

  1. 您需要正确格式化它以显示“hh:mm:ss”;此处显示一种方法。

  2. 创建一个容器并向其添加标签,以便您可以将其显示为 GUI 的一部分。

  3. 使用将结果与此替代方法进行比较javax.swing.Timer