The SwingWorker in swing is primarily used to perform more time-consuming tasks.
Some simple examples are included in the Java doc documentation.
An abstract class to perform lengthy gui-interaction tasks in a background thread. Several background threads can is used to execute such tasks. However, the exact strategy of choosing a thread for any particular swingworker are unspecified and should not being relied on .
When writing a multi-threaded application using Swing, there is the constraints to keep in mind: (Refer to Concurrency in Swing for more details):
? Time-consuming tasks should not being run on the Event Dispatch Thread. Otherwise the application becomes unresponsive.
? Swing components should is accessed on the Event Dispatch Thread only.
These constraints mean a GUI application with time intensive computing needs at least both threads:1) a thread to per form the lengthy task and 2) the Event Dispatch Thread (EDT) for all gui-related activities. This involves inter-thread communication which can is tricky to implement.
SwingWorker is designed for situations where you need to has a long running task run in a background thread and provide u Pdates to the UI either when do, or while processing. Subclasses of SwingWorker must implement the Doinbackground method to perform the background computation.
Workflow
There is three threads involved in the life cycle of a swingworker:
? Current thread: The Execute method was called on this thread. It schedules SwingWorker for the execution on a worker thread and returns immediately. One can wait for the SwingWorker to complete using the Get methods.
? Worker thread: The Doinbackground method is called on this thread. This is the where all background activities should happen. To notify Propertychangelisteners on bound properties changes use the Firepropertychange and Getpropertychangesupport m Ethods. By default there is bound properties available:state and progress.
? Event Dispatch thread: All Swing related activities occur on the this Thread. SwingWorker invokes the process and done methods and notifies any propertychangelisteners on this thread.
Often, the current thread is the Event Dispatch thread.
Before the Doinbackground method is invoked on a worker thread, SwingWorker notifies any propertychangelisteners about the The State property is change to statevalue.started. After the Doinbackground method is finished the Do method is executed. Then SwingWorker notifies any propertychangelisteners on the State property, change to Statevalue.done.
SwingWorker is only designed to be executed once. Executing a swingworker more than once won't result in invoking the Doinbackground method twice.
Sample Usage
The following example illustrates the simplest use case. Some processing is do in the background and when do you update a Swing component.
Say we want to find the ' meaning of life ' and display the result in a JLabel.
Final JLabel Label;class Meaningoflifefinder extends Swingworker<string, object> {@Overridepublic String Doinbackground () {return findthemeaningoflife ();} @Overrideprotected void Done () {try {Label.settext (get ())),} catch (Exception ignore) {}}} (new Meaningoflifefinder ()). Execute ();
The next example is useful in situations where you wish to process data as it's ready on the Event Dispatch Thread.
Now we want to find the first N prime numbers and display the results in a jtextarea. While the is computing, we want to update our progress in a jprogressbar. Finally, we also want to print the prime numbers to System.out.
Class Primenumberstask Extendsswingworker<list<integer>, integer> {primenumberstask (JTextArea TextArea, int numberstofind) {//initialize} @Overridepublic list<integer> Doinbackground () {while (! enough &&!) IsCancelled ()) {number = Nextprimenumber ();p ublish (number), Setprogress (* numbers.size ()/Numberstofind);}} return numbers;} @Overrideprotected void process (list<integer> chunks) {for (int number:chunks) {textarea.append (number + "\ n");}} }jtextarea TextArea = new JTextArea (), final jprogressbar ProgressBar = new JProgressBar (0, 100); Primenumberstask task = new Primenumberstask (TextArea, N); Task.addpropertychangelistener (New PropertyChangeListener ( {public void PropertyChange (Propertychangeevent evt) {if ("Progress". Equals (Evt.getpropertyname ())) { Progressbar.setvalue ((Integer) evt.getnewvalue ());}}); Task.execute (); System.out.println (Task.get ()); Prints all prime numbers we have got
Because SwingWorker implements Runnable, a swingworker can be submitted to an java.util.concurrent.Executor for execution.
Parameters:<t> The result type returned by this SwingWorker ' s doinbackground and get methods<v> the type used For carrying out intermediate results by this SwingWorker ' s publish and process Methodssince:1.6author:igor Kushnirskiy