Extreme Java When vanilla Java is not enough

3Apr/110

SwingWorker from JavaSE 6

So, you didn't know about SwingWorker? Neither do I, but it is a very nice addition from JavaSE 6. You can use it as a background thread (instead of Thread class) when your task needs to communicate with Swing.

SwingWorker is abstract and needs you to implement a method "doInBackground" that is the equivalent of "Thread.run". So far, no changes. First difference is that SwingWorker implements "Future", this means it will return the result of processing. Second one is you can override methods like "done" and "process", to work with the result in EDT after the task finishes and partial results, respectively.

SwingWorkers can be cancelled with "cancel(boolean)". This changes a "cancelled" flag that can be checked with "isCancelled". BTW, if the parameter is "true", an old-school "interruption" will also be made on the task.

In "doInBackground", you can also call "progress" (running in worker thread) to report partial results to "process" (in EDT).

SwingWorker has bound properties, specially "progress" (int ranging from 1 to 100, perfect for JProgressBar), and "state" (PENDING, STARTED, DONE), and two type parameters: first for the return type, second for the partial result type (if any).

I need to invest some time in my old projects (like GEBORA) to use this incredible leverage.

BTW, if you need a thread pool, pass SwingWorker to an Executor.

Filed under: Java SE Leave a comment
Comments (0) Trackbacks (0)

No comments yet.


Leave a comment

(required)


*

No trackbacks yet.