Run function on JFrame close

If you want to terminate your program after the JFrame is closed, you have to set the default close operation on your JFrame.

In your constructor of your JFrame write:

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

If you just want to call a method when the window is closed and not terminate the whole program, than go with the answer of Maroun.


Not only do you have to add the window listener, you have to set the default close operation to do nothing on close. This allows your code to execute.

frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.addWindowListener(new WindowAdapter() {
    @Override
    public void windowClosing(WindowEvent event) {
        exitProcedure();
    }
});

Finally, you have to call System exit to actually stop your program from running.

public void exitProcedure() {
    frame.dispose();
    System.exit(0);
}

You can use addWindowListener:

frame.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
        // call terminate
    }
});

See void windowClosing(WindowEvent e) and Class WindowAdapter too.


Frame.dispose() method does not terminate the program. To terminate the program you need to call System.exit(0) method