Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint

Swing Worker

In any Swing application, a single thread is responsible for painting the GUI and handling events. This thread is called the event-dispatching thread (EDT). The use of the same thread for both tasks guarantees that each event handler finishes executing before the next one executes and that GUI painting will not be interrupted by events. If an event handler must perform a lengthy task, the task needs to run in a separate thread, or else your application will become unresponsive during the execution of the event handler. On the other hand, Swing components should be accessed on the EDT only, and, unfortunately, communication between the EDT and another thread could be tricky. Therefore, if you need to access Swing components from another thread, you need to be extra-careful.

The javax.swing.SwingWorker abstract class is a utility class that helps you with time-consuming tasks in a Swing application. After you instantiate a subclass of SwingWorker, you can call its execute method to start the worker. Calling execute in turn invokes the doInBackground method on a different thread. You should write your code in this method. From within doInBackground you can call the publish method to publish intermediate data that will be received by the process method. SwingWorker invokes the process method each time the publish method is called on the EDT. Therefore, this is your chance to update any Swing component. For example, you can send intermediate results to the publish method from doInBackground and let process prints the results in a JLabel. Finally, when doInBackground finishes executing, SwingWorker will invoke the done method. In addition, there are also a cancel method to cancel a running SwingWorker and a isCancelled method that indicates if the worker has been cancelled.


  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint