Reputation: 471
I'm working with swing at the minute and I've run into a bit of a problem, I realize that it's not possible to execute a SwingWorker thread more than once from http://docs.oracle.com/javase/tutorial/uiswing/concurrency/worker.html.
My question is that is it possible to create a new instance of the same SwingWorker thread? In the code here I've called the worker thread 'worker'
SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>(){
public void doInBackGround(){
}
};
Is it possible to create more than one instance of this thread so I can call it more than once? I've tried something like
(new SwingWorker<Void, Void> worker).execute();
but this doesn't seem to work. Any help would be appreicated!
Upvotes: 0
Views: 455
Reputation: 562
What is the problem about creating a new SwingWorker every time you need it?
If you need to store some state in the instance that needs to be run many times then you can use Runnable or Callable interfaces and give that to SwingWorker for execution. You have to create the SwingWorker every time, but the Runnable or Callable instance can be the same.
In the example below the worker instance is created every time but Runnable instances are always the same.
class Foo {
private final Runnable executeInBackground;
private final Runnable executeInDone;
public Foo(Runnable done, Runnable background) {
executeInDone = done;
executeInBackground = background;
}
public void execute() {
SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
public void doInBackground() {
executeInBackground.run();
}
public void done() {
executeInDone.run();
}
};
worker.execute();
}
}
Upvotes: 2