How to create a handler for window closing in Java Swing

好久不见. 提交于 2020-01-11 02:34:12

问题


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


来源:https://stackoverflow.com/questions/13720411/how-to-create-a-handler-for-window-closing-in-java-swing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!