JDialog with WindowListener - windowClosing not fired

user800014 picture user800014 · Dec 30, 2011 · Viewed 11.3k times · Source

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?

Answer

trashgod picture trashgod · Dec 30, 2011

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);
            }
        });
    }
}