Reputation: 69259
I have run into a weird dependency when trying to cancel an anonymous SwingWorker. My current code:
private static void init() {
if (connected) {
return;
}
//final SwingWorker<Void, Void> initWorker;
final Timer noConnectionTimer = new Timer(5000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//initWorker.cancel(true);
waitObject.setTimedOut(true);
connected = false;
waitObject.process();
}
});
new SwingWorker<Void, Void>() {
@Override
public Void doInBackground() {
noConnectionTimer.setRepeats(false);
noConnectionTimer.start();
cachedInstance = new Network(Config.HOST_NAME, Config.HOST_PORT);
if (connected) {
noConnectionTimer.stop();
new Thread(cachedInstance).start();
waitObject.setTimedOut(false);
waitObject.process();
}
return null;
}
}.execute();
}
First assumption I want to be verified:
I can kill the new Network(Config.HOST_NAME, Config.HOST_PORT)
code by killing (cancelling) the SwingWorker.
So assuming my assumption is correct, I want to cancel the anonymous SwingWorker, but when I try to give it a name initWorker
, then it needs to be final such that the timer can reference it. However the SwingWorker itself needs to reference the timer aswell, so the timer also needs to be final.
So I think I managed to create a dependancy between two final variables that need eachother, how can I fix this?
Regards.
Upvotes: 2
Views: 584
Reputation: 4878
You don't have to add an ActionListener
upon creation. You could just pass null
to the Timer
's constructor and add the ActionListener
afterwards, using addActionListener
.
Upvotes: 1