33

我有一个简单的 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
        }
    }

我想打印出这条消息:

 System.out.println("Closed");

当 GUI 关闭时(按下 X 时)。我怎样才能做到这一点?

4

4 回答 4

67

试试这个。

    addWindowListener(new WindowAdapter()
        {
            @Override
            public void windowClosing(WindowEvent e)
            {
                System.out.println("Closed");
                e.getWindow().dispose();
            }
        });
于 2013-04-30T09:04:11.880 回答
1

另一种可能性可能是dispose()Window类中覆盖。这减少了发送的消息数量,并且如果默认关闭操作设置为DISPOSE_ON_CLOSE.

具体来说,这意味着添加

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

到你的班级MyGUI

注意:不要忘记调用super.dispose(),因为这会释放屏幕资源!

于 2016-02-26T14:37:50.250 回答
1

在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!");
    }
});
于 2017-08-30T06:52:19.697 回答
0

窗口事件: 有完整的程序,希望对你有帮助。公共类 FirstGUIApplication {

public static void main(String[] args) {
    //Frame
    JFrame window = new JFrame();
    //Title:setTitle()
    window.setTitle("First GUI App");
    //Size: setSize(width, height)
    window.setSize(600, 300);
    //Show: setVisible()
    window.setVisible(true);
    //Close
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.addWindowListener(new WindowAdapter() {


        @Override
        public void windowClosing(WindowEvent e) {
            super.windowClosing(e); 
            JOptionPane.showConfirmDialog(null,"Are sure to close!");
        }

        @Override
        public void windowOpened(WindowEvent e) {
            super.windowOpened(e); 
            JOptionPane.showMessageDialog(null, "Welcome to the System");
        }

    });

}

}

于 2020-04-29T12:20:45.833 回答