Wait for SwingWorker to finish
Solution 1
I think using empty loop is bad idea, SwingWorker has
protected void done()
where you can define code executed when it's finished, then you can use listerners and firing actions for that if you want to execute outside of SW
Solution 2
you need to override done
method from SwingWorker
.
From the documentation of SwingWorker#done()
Executed on the Event Dispatch Thread after the doInBackground method is finished. The default implementation does nothing. Subclasses may override this method to perform completion actions on the Event Dispatch Thread. Note that you can query status inside the implementation of this method to determine the result of this task or whether this task has been cancelled.
public class Encrypteer3 extends SwingWorker<Void, Void>{
@Override
protected Void doInBackground() throws Exception {
// background task
return null;
}
@Override
protected void done() {
// will be executed when background execution is done
}
}
and its the while(a.isDone()==false) {
which is taking time to execute.
while(a.isDone()==false) {
// do nothing
}
user1026090
Updated on June 12, 2022Comments
-
user1026090 almost 2 years
I want to wait for my SwingWorker to finish working, and then I want to execute another SwingWorker. In this case Encrypteer3 is a class that extends the SwingWorker.
My code:
input = txtTekst.getText(); key = txtKey.getText(); System.out.println("thread1 start"); Encrypteer3 a = new Encrypteer3(); a.execute(); while(a.isDone()==false){ // do nothing } input = output; key = txtKey1.getText(); System.out.println("thread2 start"); Encrypteer3 b = new Encrypteer3(); b.execute(); while(b.isDone()==false){ // do nothing }
This makes my GUI freeze and uses a lot of CPU (java uses about 95% of CPU when executing this). I think the problem is that it's constantly checking if the thread is done and that's what makes it so CPU intensive.
There is no join() method on a SwingWorker class. How can I make this less CPU intensive?
-
user1026090 over 12 yearsthe problem is that I use that SwingWorker a different number of times depending on the situation. I used the PropertyChangeListener and that did the trick! thanks for the answer
-
Hovercraft Full Of Eels over 12 years@user1026090: yes, a PropertyChangeListener is another great way to solve your problem. 1+ to you and to java, mkorbel and kowser.