As most Java programmers know, updates to Swing GUIs should only be done on the AWT event dispatching thread and the recommendation is that long-running processes be executed on a "worker" thread, with updates sent to the event dispatching thread using SwingUtilities.invokeAndWait()
or SwingUtilities.invokeLater()
.
How do you stop the user from proceeding with the application while the long-running process is completed? Do you gray out the controls and then have the worker thread reenable them using the SwingUtilities
calls mentioned above?
Is there a better alternative pattern?
Worker Threads and SwingWorker When a Swing program needs to execute a long-running task, it usually uses one of the worker threads, also known as the background threads. Each task running on a worker thread is represented by an instance of javax.swing.SwingWorker.
The SwingWorker subclass can define a method, done, which is automatically invoked on the event dispatch thread when the background task is finished. SwingWorker implements java.util.concurrent.Future. This interface allows the background task to provide a return value to the other thread.
Join the DZone community and get the full member experience. If you're writing a desktop or Java Web Start program in Java using Swing, you might feel the need to run some stuff in the background by creating your own threads. There's nothing stopping you from using standard multi-threading techniques in Swing, and the usual considerations apply.
Hopefully you can see from this example how you might use SwingUtilities.invokeLater () in order to communicate between UI and worker threads. You can think of invokeLater as a simple callback to the UI for sending whatever updates you need. SwingWorker<T,V> can be used similarly to invokeLater, but each has its strong points.
I would consider 3 solutions :
CardLayout
, add 2 components. The first is the panel that hosts the components to inactivate, and the second is a panel showing a "loading" or "please wait" message. A simple JLabel
in a Gridbaglayout
does the trick. Then, you just have to switch from one to another. I use this technique for places where a result of a computation/request is to be displayed.LayeredPane
, or you can use a dedicated utility. JXLayer can do that (I read that JXLayer will be included in Java 7, so this may become the 'standard' solution to this kind of problem).There are several ways and the selection of which, mostly depends on the design and layout of your GUI.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With