Arianule
Arianule

Reputation: 9043

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. 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.

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


}

Upvotes: 8

Views: 13338

Answers (3)

MockerTim
MockerTim

Reputation: 2483

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.

Upvotes: 2

tomgi
tomgi

Reputation: 1422

Check this class http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Timer.html scheduleAtFixedRate(TimerTask task, long delay, long period) is probably what you need.

Upvotes: 1

isah
isah

Reputation: 5341

What do you want to improve? It looks ok, while(runner == null) not necessary, you're initialising runner just above.

Upvotes: 2

Related Questions