views:

121

answers:

1

I'm having problems passing information, updating progress and indicating "done" with a SwingWorker class that is not an encapsulated class.

I have a simple class that processes files and directories on a hard drive. The user clicks on the Start button and that launches an instance of the SwingWorker.

I would like to print the names of the files that are processed on the JTextArea in the Event Driven Thread from the SwingWorker as update a progress bar. All the examples on the web are for an nested class, and the nested class accesses variables in the outer class (such as the done method). I would also like to signal the Event Driven Thread that the SwingWorker is finished so the EDT can perform actions such as enabling the Start button (and clearing fields).

Here are my questions: 1. How does the SwingWorker class put text into the JTextArea of the Event Driven Thread and update a progress bar?

  1. How does the EDT determine when the {external} SwingWorker thread is finished?

{I don't want the SwingWorker as a nested class because there is a lot of code (and processing) done.}

+2  A: 

A SwingWorker is still a class you can extend and pass in any information it requires to do its job, whether or not it's encapsulated in another class. So you could pass in the JTextArea as a "target text area" in the constructor, store it as a member variable, and then update the text area in the process(List<V>) method.

The EDT doesn't determine when the worker is finished: The worker itself knows it has completed its job because the doInBackground() method finishes. The code that wraps up the worker detects the completion of doInBackground() and then invokes the done() method on the EDT. (The ability of the swing worker to handle all the changes in threads for you automatically is one of the things that makes it so good.)

In your done() implementation you could inform your GUI of completion by calling back via an observer object - again, something you could pass in to the worker's constructor.

See this tutorial on SwingWorker for a description of how to impement the different methods. The trail on progress bars includes a section on using a progress bar in a swing worker.

Ash