6
votes

I have a Java project.
I have a JFrame with a handler attached to it like so

frame.addWindowListener(new WindowAdapter() {

            public void windowClosing(WindowEvent evt) {
                this.setEnabled(true);

            }
        });

But, on that frame I also have a close button (to make it more user friendly) and that "close" button calls the frame dispose method. Now, when I close the frame by clicking the little x button on the top right corner, the WindowListener is called. But the event doesn't fire when I invoke the dispose method.
should I Invoke some other method to close, so the WindowListener fires, or maybe implement another listener?

2

2 Answers

9
votes

You should take a look at the WindowListener interface.

windowClosing(): Invoked when the user attempts to close the window from the window's system menu. (window X button)

windowClosed(): Invoked when a window has been closed as the result of calling dispose on the window.

So, windowClosing() is called only when the user clicks the X button of the window; windowClosed() is called when the dispose() event is invoked, so it is always invoked:

  • if the user closes the frame using the windows X button
  • if the frame is programatically closed by code
    JFrame myFrame = new JFrame();
    myFrame.addWindowListener(new java.awt.event.WindowAdapter() {
        @Override
        public void windowClosed(java.awt.event.WindowEvent windowEvent) {
            // your code
        }
    });

Source: https://alvinalexander.com/blog/post/jfc-swing/closing-your-java-swing-application-when-user-presses-close-but

3
votes

on that frame i also have a close button (to make it more user friendly)

Check out the Closing an Application solution to handle this. All you really need to do is add the "ExitAction" to your button, but you can use the whole approach if you want.