Terminate running threads on JFrame close

前端 未结 3 1727
梦谈多话
梦谈多话 2021-02-09 11:09

How do I invoke extra operations when the user closes a JFrame window? I have to stop existing threads.

As I understand it, setDefaultCloseOperation(J

3条回答
  •  既然无缘
    2021-02-09 11:41

    Using JFrame.EXIT_ON_CLOSE actually terminates the JVM (System.exit). All running threads will automatically be stopped.

    If you want to perform some action when a JFrame is about to close, use a WindowListener.

    JFrame frame = ...
    frame.addWindowListener(new WindowAdapter() {
        @Override
        public void windowClosing(WindowEvent e) {
            // close sockets, etc
        }
    });
    

提交回复
热议问题