views:

50

answers:

3

I have a start and stop button. I was told that I must use a SwingWorker. The code that I have now works fine. I start it and I stop it. But what if i want to start it again..? I am reading that the doinBackground method will only be executed once. Is there a way to fire it off again..??

Right now I cannot create a new instance of that Swing Worker because in my Swing Worker I have a while loop that says while(isSet) which is set to True when I click on the Start Button and set to False when I click on the stop button.

Is there a way around this..??

Thanks

A: 

Each SwingWorker is designed to be executed once, as you say. In that respect each object represents a single execution.

So one valid (and probably the most straightforward) way to do what you're after, is to create a new SwingWorker for each click of the start button, if you really do want to spawn another instance of the action each time.

Andrzej Doyle
I cannot do this. When I click the start button I set a boolean in there. In the doinBackground() method I loop over something until it is set to false (which is when you hit the stop button). If I create a new instance everytime, i will not know when this boolean is flagged.
Biggs
You should edit your question to explain this.
DJClayworth
DJClayworth.... thanks I have edited my question. Can you provide me with a basic code snipit of what you were referring too..?? (i.e. having an object encapsulate the SwingWorker).. Thanks..!
Biggs
+2  A: 

The SwingWorker API doc answers your question:

SwingWorker is only designed to be executed once. Executing a SwingWorker more than once will not result in invoking the doInBackground method twice.

SwingWorker API docs

You'll need to create a new SwingWorker instance each time your start button is pressed.

darri
+1  A: 

What I would suggest is having an object encapsulate the SwingWorker. When the "go" button is pressed have that object create a SwingWorker and set it going. When the "stop" flag is set have the SwingWorker finish itself and tell the encapsulating object that it's finished. When the "go" button is pressed again the encapsulating object creates a new SwingWorker, and so on.

DJClayworth
This sounds exactly what I want to do. Can you post a code example of this..?? Thank You
Biggs
Just looking for a very basic example. Thanks
Biggs