Re: Can you get this SwingWorker code to work more than once
On 8/9/2012 11:55 AM, email@example.com wrote:
On Thursday, August 9, 2012 11:48:04 AM UTC-4, Eric Sosman wrote:
On 8/9/2012 11:24 AM, ... wrote: > Here is a project that works
perfectly only the first time. [...] Quoth the JavaDoc: "SwingWorker is only
designed to be executed once. Executing a SwingWorker more than once will not
result in invoking the doInBackground method twice." If you want to do a
background task N times, you'll need N instances of SwingWorker, one per task
execution. -- Eric Sosman firstname.lastname@example.org
So, I want a project to do the following:
(1) Display a button when the project is run,
(2) When the user presses the button, a label is displayed.
(3) The project next executes three long "for" loops such as in a previous post of this thread.
(4) When the three "for" loops are finished, the label disappears.
Question: How can I repeatedly do steps (2) through (4) above when a project is started?
"When a project is started?" Or "Each time the user presses
the button?" I'll assume the latter.
When you set up the button, create an ActionListener to be
notified of button presses. The listener's actionPerformed()
method will display the label (that's #2 above), create a SwingWorker,
call the worker's execute() method, and return.
Because execute() was called, Java will ("eventually," but in
practice "fairly soon") start the SwingWorker on a background
thread and call its doInBackground() method. This method runs the
long loops (#3) and then returns. Note that since it's executing
on a background thread and not on the event dispatch thread (EDT),
doInBackground() should do almost nothing to or with the GUI: Only
a very few bits of Swing are thread-safe.
After doInBackground() returns, Java will ("eventually/soon")
call the SwingWorker's done() method. This call runs on the EDT,
so the done() method can manipulate the GUI: It can make the label
invisible or even remove it from its container (#4).
Next time the user presses the button, the actionPerformed()
method creates a brand-new SwingWorker and the same sequence of
actions repeats. You can't re-use the old SwingWorker instance,
but you can create a new instance of the same class, running the
All this and more is covered in the Java Tutorial's chapter
on Swing concurrency,