Java Swing为EXIT_ON_CLOSE添加动作侦听器

时间:2013-04-30 08:58:18

标签: java swing jframe windowlistener

我有一个简单的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 个答案:

答案 0 :(得分:53)

试试这个。

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

答案 1 :(得分: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!");
    }
});

答案 2 :(得分:0)

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

具体地说,这意味着添加

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

到您的班级MyGUI

注意:请勿忘记拨打super.dispose(),因为这会释放屏幕资源!

答案 3 :(得分: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");
        }

    });

}

}