I've created a gui that has 3 buttons; connect, disconnect, abort. They all share a common SwingWorker thread, but for some reason the thread never finishes unless I hit the abort button.
I didn't write any code for the disconnect button yet, but even so, it's not relevant to my question. However, why doesn't the thread just finish and print the Done
statement? My guess is that it's getting stuck in the this.isCancelled()
loop, but even if I do:
while(!this.isCancelled() || !this.isDone()) { // run loop }
it never prints Done
The thread is only finished once I hit the abort button. I'm using the isCancelled()
loop method because this seems to be the recommended way of canceling a SwingWorker.
I'm posting only the relevant code below because there are literally hundreds of lines.
private class ButtonListener implements ActionListener {
private MyWorker worker;
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource().equals(connectButton)) {
worker = new MyWorker(activityTextArea);
worker.execute();
activityTextArea.append("Connect Button Pressed");
}
if(e.getSource().equals(disconnectButton)) {
activityTextArea.append("Disconnect Button Pressed");
}
if(e.getSource().equals(abortButton)) {
worker.cancel(true);
activityTextArea.append("Abort Button Pressed");
}
}
}
Here is the SwingWorker:
public class MyWorker extends SwingWorker<Void, Void> {
private JTextArea textArea;
MyWorker(JTextArea textArea) {
this.textArea = textArea;
}
private void startWorker() {
ProcessBuilder pb = new ProcessBuilder();
pb.command("aCmd");
Process p;
try {
p = pb.start();
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while((line = br.readLine()) != null) {
textArea.append(line + "\n");
}
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
protected Void doInBackground() throws Exception {
// TODO Auto-generated method stub
boolean isFirstTime = true;
while(!this.isCancelled()) {
if(this.isDone()) { break; }
Thread.sleep(3000);
if(isFirstTime) {
startWorker();
isFirstTime = false;
}
}
return null;
}
@Override
protected void done() {
textArea.append("Done\n");
}
}