JDialog with WindowListener - windowClosing not fi

2019-06-26 08:14发布

问题:

I have a class that extends JDialog that have a window listener:

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...
                }

            });
     }

}

When i click in the X button, nothing happens. And I don't see the print of "closing..."

What I am missing?

回答1:

Works for me. See also this related 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);
            }
        });
    }
}