SwingWorker(javax.swing.SwingWorker) is one of those handy classes for any swing developer’s toolbox. Originally a piece of OSS, the good folks on the java team decided to include it into the JavaSE 6 standard API. Whats more is that its API is in simplicity itself. lets look at it:
- execute: called from whatever thread that created the SwingWorker( in most cases it will be the EDT)
- doInBackground: this is where the magic happens, this is your eqivalient of Thread’s run method.
- publish: From inside doInBackground, this allows you to push items to the process method(described next) to be worked on in the EDT.
- process: this method consumes objects from publish on the EDT so work on them, and any swing components that need to be modified are done so on the EDT.
- done: this method is calledwhen doInBackground has completed its execution and allows for any cleanup tasks that must occur on the EDT
You can create a SwingWorker with nothing more than doInBackground to get work done. Its real power however comes from the publish/process/done methods. these methods make sure you do not violate the Single Thread Rule.
SwingWorker is an essential tool that should not be overlooked.
Saturdays, Swing Zen looks to distill Swing down into its essential elements for those new to Swing development.