views:

41

answers:

1

I want to create a simple clock using Java. The code is so simple that I will give an example:

for(int i=0;i<=60;i++)
   jLabel11.setText( Integer.toString(i) );

The problem is while I'm running my program the result didn't show each update in sequence. It show only the 60 digit immediately, without showing the change from 1 to 2 to 3 ...

How can i fix this problem?

+1  A: 

The problem is that changes to the UI should run on the event dispatch thread, but blocking this loop (and blocking the UI) will stop the screen from repainting. Instead, use a timer to perform regular updates, e.g.

Timer timer = new Timer();

ActionListener updater = new ActionListener()
{
   int count;
   public void actionPerformed(ActionEvent event) {
      jLabel11.setText( Integer.toString(count++) );
      if (count==60)
         timer.stop();
   }
}
timer.setDelay(100);
timer.addActionListener(updater);
timer.start(); 

See the Sun Tutorial - How to use Swing Timers.

mdma
To be clear that is `javax.swing.Timer`, not any other sort of `Timer` that you might find. Also note that `javax.swing.Timer` should only be used on the AWT Event Dispatch Thread (EDT), which seems like an unnecessary restriction to me.
Tom Hawtin - tackline
@Tom Hawtin - tackline: Instances of `javax.swing.Timer` share a common `TimeQueue` using a single thread; `actionPerformed()` runs on the EDT as a convenience.
trashgod
@trashgod I mean that the `Timer` should only be set up on the EDT.
Tom Hawtin - tackline