File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Swing / AWT / SWT and the fly likes Runnable Thread to update GUI components Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "Runnable Thread to update GUI components" Watch "Runnable Thread to update GUI components" New topic

Runnable Thread to update GUI components

Pablo Mino

Joined: Aug 11, 2009
Posts: 28
Hi, I have a GUI with some fields and they get updated when I start a class that implements Runnable. I'm being forced to send the components in the class constructor in order for them to be used on the Runnable Thread side. For instance lets say I have a Jlabel that is a counter and that in my Runnable class I got the integer value ++, so I pass the JLabel to the Runnable class because otherwise the value won't change with time.

Is this the right way? because having swing components in the logic layer looks odd...
Pablo Mino

Joined: Aug 11, 2009
Posts: 28
Ok I found a way to pass things between threads by using volatile.

I got 5 different messages that need to be passed to the GUI and not mentioning the volatile boolean that stops the thread. Is this the way?
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 38075
Pablo Mino wrote:. . . Is this the way?

You must not access Swing from any thread but the Event Despatch Thread, because Swing components are not thread-safe. See this.

I am moving this thread to the GUIs forum.
Rob Camick
Ranch Hand

Joined: Jun 13, 2009
Posts: 2156
You can also use a Swing Worker. Read the section from the Swing tutorial on Concurrency for a complete discussion of this issue.
jQuery in Action, 2nd edition
subject: Runnable Thread to update GUI components
Similar Threads
Issues with hiding a panel
extends thread as well as implements Runnable
Let one Thread set a Boolean and edit a ArrayList in another Thread
Mouse shift event coding - to trigger a predetermined sequence of images to a GUI