Mattias
Mattias

Reputation: 1110

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

Upvotes: 18

Views: 41381

Answers (4)

Muhammad
Muhammad

Reputation: 36

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

Upvotes: 2

Maroun
Maroun

Reputation: 95948

You can use addWindowListener:

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

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

Upvotes: 26

Gilbert Le Blanc
Gilbert Le Blanc

Reputation: 51445

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

Upvotes: 20

Martin Seeler
Martin Seeler

Reputation: 6982

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.

Upvotes: 1

Related Questions