• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Why the JLabel is not updated immediately?

 
Ranch Hand
Posts: 96
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi all,

I am a beginner in Swing programming. I have a JFrame with a button and a label below:




I expect that the countLabel is updated after every second.
However, when I click the start button, the countLabel is not updated after every second. It is only updated at the 5th second with the value 4.
Can anyone explain this for me?



 
Bartender
Posts: 11497
19
Android Google Web Toolkit Mac Eclipse IDE Ubuntu Java
 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
lblInfo.paintImmediately(lblInfo.getVisibleRect()); will do the job.
 
Rancher
Posts: 3324
32
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The Thread.sleep(...) causes the Event Dispatch Thread (EDT) to sleep which means the GUI can't repaint itself until the looping code has finished executing.

Don't use a loop and don't use Thread.sleep().

Instead you will want to use a Swing Timer to schedule animation. Read the section from the Swing tutorial on How to Use Swing Timers for more information.

Or you could use a SwingWorker as described in the above link on "Concurrency in Swing". The SwingWorker executes on a separate Thread, so you could use Thread.sleep() in this case and then "publish" each result as it becomes available. Read the section on "Tasks That Have Interim Results" from the "Concurrency" link for more information and working examples.

Don't use paintImmediately(...). This bypasses normal painting procedures and indicates an improper design of your code.
 
reply
    Bookmark Topic Watch Topic
  • New Topic