Reputation: 5398
I am having some trouble with my swingworker thread, and the issue is when i cancel. Essentially, I have a a start button, which when clicked runs my swingworker.
From here my swing worker does a number of small things but the main thing is that it completes some long running reflection calls.
I also have a cancel button - which as you probably guessed cancels my swingworker. The issue however is that I have a bug which I just cannot pinpoint.
After cancelling the application mid way through its first run, the swing worker cancels perfectly, however, if i then click start again and let it run all the way through when it completes - the thread seems to pick back up from where i cancelled on the first run :/ . I have no idea why this is and it apepears as if the cancelled thread is resuming and actually remembering state. I know this is happening because on my gui I have a JLabel that says "processing element 1 of 15..." and it jumps back to the cancelled point.
public class Test
{
private SwingWorker<Object, Integer> swingworker = initiate();
private void startListener()
{
start.addActionListener(new ActionListener ()
{
public void actionPerformed(ActionEvent e)
{
runIt();
}
});
}
private void runIt()
{
try
{
if(swingworker .isDone())
swingworker = getSwingWorker();
swingworker.execute();
}
catch (HeadlessException e) { }
catch(Exception e){LogFileWriter.log(e);}
}
private SwingWorker<Object, Integer> getSwingWorker()
{
return new SwingWorker<Object, Integer>()
{
Object o;
protected Object doInBackground() throws Exception
{
//do some short calcs
doLongCalc();
return o;
}
protected void done()
{
if(!swingworker .isCancelled()) {} //chnage the gui values like enable / disable button }
else{}//it was cancelled so stop progress bar and stuff
}
};
}
private void cancelListener()
{
cancel.addActionListener(new ActionListener ()
{
public void actionPerformed(ActionEvent e)
{
if(swingworker.getState() == SwingWorker.StateValue.STARTED || swingworker.getState() == SwingWorker.StateValue.DONE)
{
swingworker .cancel(true);
}
}
});
}
private void doLongCalc()
{
//wrap the taks in checks for cancelled or not
if(!swingworker.isCancelled())//do something
if(!swingworker.isCancelled())//do something
if(!swingworker.isCancelled())//do something
if(!swingworker.isCancelled())//do something
}
}
Upvotes: 0
Views: 378
Reputation: 5398
I had found out that I was not actually catching and dealing with an exception correctly. As such the programme flow was continuing where it should have been stopping.
Upvotes: 0
Reputation: 2762
Swingworker is designed to execute once, You can have a look at following post How cancel the execution of a SwingWorker?
This might resolve your issue or you will find answer.
Upvotes: 2