Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if my window listener is working

I'm trying to see if my window listener is working. I was hoping to print out a message in the console before I call dispose in the windowClosed method but it doesn't print anything. I'm not really sure if I'm doing something wrong - is there a way to check?

    public class MyClass extends JFrame {
    . . . 
             this.addWindowListener(new WindowAdapter() {

             @Override
             public void windowClosed(WindowEvent e) {
                 System.out.println("I'm in the listener");
                 dispose();
             }
        });

    . . .
}
like image 434
user3281466 Avatar asked Jan 22 '26 11:01

user3281466


2 Answers

I think you want windowClosing, which is called when the user tries to close the window. windowClosed is called after the window has been disposed, so it doesn't make sense to try to dispose it from there.

like image 157
Boann Avatar answered Jan 25 '26 01:01

Boann


windowClosing is always fired.
windowClosed will be fired when you use:

setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

But the overridden method should be like this,

           @Override
           public void windowClosed(WindowEvent e) {
               System.out.println("I'm in the listener");
               System.exit(0);
           }
      });

Here you can not use dispose() method since this method will be called after the frame is disposed. If dispose() method is called then this will make windowClosed() method execute infinitely.

like image 29
RKC Avatar answered Jan 25 '26 02:01

RKC



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!