How to create a handler for window closing in Java

2019-02-13 15:31发布

问题:

I'm trying to call a function to do cleanup when my window (created with Java Swing) is closed . In my initialization code I do this:

public class FormLogin extends JFrame{
    private void initComponents(){
        ...
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt){
                formLoginWindowClosed(evt);
            }
        });
        ...
    }
}

But the function "formLoginWindowClosed" is never called when I press the exit button. I've also tried creating the listener with java.awt.event.WindowAdapter as an argument, but it didn't work either. How should I create the listener for window closing? Thanks in advance.

回答1:

With the frame set to exit on close, windowClosed will never be called, mostly because the system has already exited before the event can be raised.

Try using windowClosing instead.

Alternatively, you could use a shut down hook

  • JVM Shutdown Hook in Java
  • Design of the Shutdown Hooks API
  • Java Shutdown hook – Runtime.addShutdownHook()