I have a certain task which I run at scheduled intervals. Basically I show a camera feed on a Label in a JFrame. However when I exit the JFrame the application seems to run. How can I stop it? I have stripped out the details of the code, just leaving the relevent parts in
public class TaskCLass extends JFrame {
JPanel p;
JLabel l;
Timer timer;
public TaskCLass() {
p = new JPanel();
l = new JLabel("Window");
add(p);
p.add(l);
setSize(700, 600);
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.out.println(e);
timer.purge();
timer.cancel();
System.exit(1);
}
public void windowClosed(WindowEvent e) {
System.out.println(e);
timer.purge();
timer.cancel();
System.exit(1);
}
});
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
startTask();
}
public static void main(String[] args) {
new TaskCLass();
}
public void startTask() {
TimerTask t = new TimerTask() {
@Override
public void run() {
//.........
}
};
timer = new Timer();
timer.schedule(t, 0, 200);
}
}
Better to use a Swing Timer if the scheduled code is modifying the GUI. Otherwise if you are using the non-Swing Timer than you need to shut it down with cancel().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With