Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swing stop timer when exiting jframe

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);
    }


}
like image 591
ChrisGeo Avatar asked Oct 22 '22 12:10

ChrisGeo


1 Answers

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().

like image 84
Nándor Krácser Avatar answered Oct 24 '22 02:10

Nándor Krácser