Search code examples
javaswingjframewindowlistener

Run function on JFrame close


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

Solution

  • You can use addWindowListener:

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

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