Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
    }
});
like image 930
Mattias Avatar asked May 04 '13 08:05

Mattias


4 Answers

You can use addWindowListener:

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

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

like image 178
Maroun Avatar answered Nov 09 '22 01:11

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);
}
like image 40
Gilbert Le Blanc Avatar answered Nov 09 '22 00:11

Gilbert Le Blanc


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

like image 2
Muhammad Avatar answered Nov 09 '22 00:11

Muhammad


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.

like image 1
Martin Seeler Avatar answered Nov 09 '22 00:11

Martin Seeler