简体   繁体   English

使用线程创建数字时钟

[英]Creating digital clock using a thread

I am trying to create a digital clock using a Thread as this seems to me the logical way one would do it. 我正在尝试使用线程创建数字时钟,因为在我看来这是一种合理的方式。 I am not sure if I am going about it the right way but what I had in mind is to create the initial current System time using the JFrame constructor and display it as text using a label. 我不确定是否要以正确的方式进行操作,但是我想到的是使用JFrame构造函数创建初始的当前系统时间,并使用标签将其显示为文本。 In the constructor I then create the thread object with which to update the time. 然后,在构造函数中,我创建用于更新时间的线程对象。

Struggling a bit and was hoping for some advice as to how to do it right. 挣扎了一点,希望就如何正确地做一些建议。

setDefaultCloseOperation((JFrame.EXIT_ON_CLOSE));
        setBounds(50, 50, 200, 200);

        JPanel pane = new JPanel();
        label = new JLabel();

        //Font localTime = new Font("Lumina", Font.BOLD , 24);

        pane.add(label);
        add(pane);
        sdf = new SimpleDateFormat("HH:mm:ss");
        date = new Date();

        s = sdf.format(date);
        label.setText(s);
        setVisible(true);
        runner = new Thread(this);

        while(runner == null)
        {
            runner = new Thread(this);
            runner.start();

        }

This is then my run() method to update the clock every second. 这就是我的run()方法,用于每秒更新一次时钟。

public void run()
{
    while(true)
    {
        try
        {
            Thread.sleep(1000);
            sdf = new SimpleDateFormat("HH:mm:ss");
            date = new Date();
            s = sdf.format(date);
            label.setText(s);
        }
        catch(Exception e){}

    }

Main method. 主要方法。

public static void main(String[] args)
{
    new DigitalClock().setVisible(true);


}

What do you want to improve? 您想改善什么? It looks ok, while(runner == null) not necessary, you're initialising runner just above. 看起来没问题, while(runner == null)不必要,但是您正在上面初始化Runner。

The label state should be updated in the Event Dispatch Thread. 标签状态应在事件调度线程中更新。

You need to add the following modification: 您需要添加以下修改:

    SwingUtilities.invokeLater(new Runnable() {

        @Override
        public void run() {
            label.setText(s);
        }
    });

instead of simply updating the label from the separate thread. 而不是简单地从单独的线程更新标签。

It's worth to have a look at the simple description of The Swing GUI Freezing Problem and it's simple solution. 值得一看“ Swing GUI冻结问题”的简单描述及其简单的解决方案。

检查此类http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Timer.html scheduleAtFixedRate(TimerTask任务,长时间延迟,长时间)可能是您需要的。

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

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