views:

243

answers:

6

I added an window state listener as follow:

this.addWindowStateListener(new WindowAdapter() {
        public void windowClosing(WindowEvent e) {
            ExitAction.getInstance().actionPerformed(null);
        }

    });

But when I'm using the X close button the event is not called. I think it's something to do with netbean jdesktop framework. But I can't find what could be the problem. Thanks for your help.

+1  A: 

Normally you use a WindowListener for this.

Check out Closing an Application for an approach I use, although I must admit I've never tried it with Netbeans since I don't use an IDE.

camickr
A: 

As the Java documentation says, to actually close the window the listener should invoke the window's dispose or setVisible(false) method.

Drewen
+4  A: 

windowClosing is part of the WindowListener interface. Use addWindowListener instead of addWindowStateListener.

jackrabbit
+1. note that a `WindowStateListener` is used to handle events that are triggered when the window is minimized or maximized, etc, but not closed.
akf
A: 

As others have pointed out the WindowListener is what you are after... but you should do this from now on when overriding a method:

this.addWindowStateListener(
    new WindowAdapter() 
    {
        @Overrides
        public void windowClosing(WindowEvent e) 
        {
            ExitAction.getInstance().actionPerformed(null);
        }

    });

Then the compiler will tell you when you are not actually overriding a method and are instead adding a new method (that in this case will never be called).

TofuBeer
WindowAdapter is both a WindowListener and a WindowStateListener. The problem here is that it's being added as a WindowStateListener so the methods it has as a WindowListener are not called.
lins314159
ah true, I didn't know it implemented more than WindowListener. How odd... apparently they added that in 1.4. Before 1.4, if Java had annotations, what I said would have worked :-) (not deleting the answer since it is valid as a general rule just not in this specific case)
TofuBeer
+2  A: 

Not answering your question directly (since an answer has already been given), but I assume you want to quit your program (or just hide a window) on exit. There is a shorter solution for these situations:

window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Bozho
A: 

Thank you everyone for helping me solve the problem. I don't fully understend it but the following code solve the problem:

    Frame[] frames = Frame.getFrames();
    for(Frame f: frames){
        f.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                ExitAction.getInstance().actionPerformed(null);
            }

        });
    }

It look as if the framework add additional frames. Thanks,

Guy