Run function on JFrame close

Mattias picture Mattias · May 4, 2013 · Viewed 34k times · Source
void terminate() {}
protected JFrame frame = new JFrame();

How can I get frame to run the terminate function when I press the close button?

Edit: I tried to run this, but for some reason it doesn't print test (however, the program closes). Does anyone have an idea what could be the problem?

frame.addWindowListener(new WindowAdapter() {
    public void WindowClosing(WindowEvent e) {
        System.out.println("test");
        frame.dispose();
    }
});

Answer

Maroun picture Maroun · May 4, 2013

You can use addWindowListener:

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

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