Swing stop timer when exiting jframe

I have a specific task that I run at scheduled intervals. I mainly show the camera on a shortcut in a JFrame. However, when I exit JFrame, the application works. How can I stop him? I deleted the code details, leaving only the relevant 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); } } 
+4
source share
1 answer

It is better to use Swing Timer if the planned code changes the GUI. Otherwise, if you use a non-Swing Timer , you need to close it using undo () .

+3
source

All Articles