开发者

Is there a way to Start and Stop a SwingWorker more than once..?

开发者 https://www.devze.com 2023-01-08 03:40 出处:网络
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 d

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


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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号