views:

189

answers:

3

I have a system tray UI in Java that requires a schedule database poll. What is the best method for spawning a new thread and notifying the UI?

I'm new to Swing and it's threading model.

+5  A: 

SwingWorker is the exact thing designed to do this.

It allows you to run a task that won't block the GUI and then return a value and update the GUI when it is done.

Java has a great tutorial on how to use SwingWorker.

Basically do the database pull in the doInBackground() method. And, in the done() method, update your GUI.

jjnguy
+5  A: 

As jinguy mentioned SwingWorker should be the first place you look at. Wikipedia, of all places, has some interesting examples that may be good to look at before you tackle the JavaDocs.

Uri
I never know that Wikipedia had such a great article on `SwingWorker`. I'd upvote you, but I don't wanna lose my place on top of the sort order...(sorry)
jjnguy
There ya go. `+1`!
jjnguy
Grr, but if you keep getting upvotes, I'm never going to pass you in the 'Questions tagged Java' `:P`
jjnguy
+2  A: 

As jjnguy mentioned, SwingWorker helps abstract away the complexity here, but basically you do the work in a new thread, and when the method comes back, you need to update the GUI in the swing thread. If you aren't using SwingWorker, the underlying method is SwingUtilities (or EventQueue) .invokeLater(Runnable).

Do not update anything Swing related (including models) outside of the swing queue, unpredictable things will happen. And don't attempt to hold a reference to the queue and use that, as queues are suspended and replaced (if for example you open a model dialog box).

Yishai