Creating a Digital Clock Using a Stream

I am trying to create a digital clock using Thread, as it seems logical to me how to do this. I'm not sure if I will do it right, but what I had in mind was 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 a stream object with which to update the time.

After suffering a little, and hoped for some advice on 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 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){} } 

The main method.

 public static void main(String[] args) { new DigitalClock().setVisible(true); } 
+8
java
source share
3 answers

Tag status must be updated in Thread Dispatch Thread.

You need to add the following modification:

  SwingUtilities.invokeLater(new Runnable() { @Override public void run() { label.setText(s); } }); 

instead of just updating tags from a separate thread.

Worth a look at a simple description The task of freezing a Swing GUI is a simple solution.

+2
source share

What do you want to improve? It looks fine, while(runner == null) not needed, you initialize the runner a little higher.

+2
source share

Check this class out 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.

+1
source share

All Articles