Java Swing adding Action Listener for EXIT_ON_CLOSE

让人想犯罪 __ 提交于 2019-11-26 11:26:08

问题


I have a simple GUI:

    public class MyGUI extends JFrame{

        public MyGUI(){
           run();
        }

        void run(){
           setSize(100, 100);
           setVisible(true);
           setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);// maybe an action listener here
        }
    }

I would like to print out this message:

 System.out.println(\"Closed\");

When the GUI is closed (when the X is pressed). How can I do that?


回答1:


Try this.

    addWindowListener(new WindowAdapter()
        {
            @Override
            public void windowClosing(WindowEvent e)
            {
                System.out.println("Closed");
                e.getWindow().dispose();
            }
        });



回答2:


Write this code within constructor of your JFrame:

this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
this.addWindowListener(new java.awt.event.WindowAdapter() {
    @Override
    public void windowClosing(java.awt.event.WindowEvent e) {
        System.out.println("Uncomment following to open another window!");
        //MainPage m = new MainPage();
        //m.setVisible(true);
        e.getWindow().dispose();
        System.out.println("JFrame Closed!");
    }
});



回答3:


Another possibility could be to override dispose() from the Window class. This reduces the number of messages sent around and also works if the default close operation is set to DISPOSE_ON_CLOSE.

Concretely this means adding

@Override
public void dispose() {
    System.out.println("Closed");
    super.dispose();
}

to your class MyGUI.

Note: don't forget to call super.dispose() as this releases the screen resources!



来源:https://stackoverflow.com/questions/16295942/java-swing-adding-action-listener-for-exit-on-close

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