带有WindowListener的JDialog - 未触发windowClosing

时间:2011-12-30 16:13:10

标签: java swing jdialog windowlistener

我有一个扩展JDialog的类,它有一个窗口监听器:

class MyClass extends JDialog {

     public MyClass() {
         setDefaultCloseOperation( JDialog.DO_NOTHING_ON_CLOSE );
         addWindowListener( new WindowAdapter() {

                @Override
                public void windowClosing(WindowEvent e) {
                    System.out.println("closing...");
                    //do something...
                }

            });
     }

}

当我点击X按钮时,没有任何反应。我没有看到“关闭......”的印刷品。

我缺少什么?

1 个答案:

答案 0 :(得分:9)

适合我。另请参阅此相关example

import java.awt.EventQueue;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JDialog;

class MyClass extends JDialog {

    public MyClass() {
        setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
        addWindowListener(new WindowAdapter() {

            @Override
            public void windowClosing(WindowEvent e) {
                System.out.println("closing...");
                //do something...
            }
        });
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                MyClass m = new MyClass();
                m.setVisible(true);
            }
        });
    }
}