Terminate running threads on JFrame close

J.Olufsen picture J.Olufsen · Jun 3, 2012 · Viewed 15.9k times · Source

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

As I understand it, setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); causes the frame to be closed and its thread to be stopped. Should threads be closed after JFrame.EXIT_ON_CLOSE?

Client:

static boolean TERMINATE = false;
public static void main(String[] args) {
// some threads created
 while(true) {

                if(TERMINATE){
                         // do before frame closed
                    break;
                         }
              }

}
    private static JPanel startGUI(){
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            JPanel gui = new JPanel();
             f.add( gui);
             f.setSize(500,500);
             f.setVisible(true);
             return gui;
        }

I need to close sockets the thread's working with. What is the best practice to do that?

Answer

Jeffrey picture Jeffrey · Jun 3, 2012

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