Originally posted by Barry Brashear: If a swing application is starting a Thread from which it will get data and populate some Swing control after the Thread finishes, how is this accomplished.
It is accomplished the same way any two classes which need to communicate with each other does it. You need a reference from the instance to another -- meaning a way to get from the database object to the swing component.
There is another issue though. The swing utilites are not threads safe. Most operations need to be done from the event dispatching thread. To run something on the event thread, take a peek at the SwingUtilities class -- the invokeLater() and invokeAndWait() methods to be exact.
Could you have the database object post an event that the swing object is listening for? Then call a method containing the invokeLater to update the swing components?
Shyam Prasad Murarka
Joined: May 02, 2005
Dear Barry, You could do something like this:
Note: The call to your other class is executed by the thread itself.
With Best Regards,
Shyam Prasad Murarka
Joined: Dec 01, 2003
//Update your swing components here
There is exactly where you do NOT want to update your swing components. As Henry said above, the swing components are not thread safe. This is what he means by that.
However, you could fire an event that is noticed by your gui which will update the data in the event dispatch thread. You can look into the Observer/Observable pattern as well as the invokeLater() method.
Joined: Jan 29, 2003
The key is the invokeLater() or invokeAndWait() methods on SwingUtilities. That will put some command in a queue and invoke it on the GUI thread.
An event-driven observer-observable structure is a good thing for separation of concerns, but usually the event is generated by the worker thread and all code runs on the worker thread, so still need one of the invoke methods in the observer.
That's how I made my stuff run anyhow. Before I learned about SwingUtilities my updates from worker threads were unpredictable even with a nice pub-sub thing going on between the model & view. I changed to use the invokeLater method and all is well.
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Joined: May 01, 2005
Originally posted by Barry Brashear: Could you have the database object post an event that the swing object is listening for? Then call a method containing the invokeLater to update the swing components?