Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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.

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).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top