Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JFrame catch dispose event

Tags:

java

jframe

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?

like image 424
Andrej Avatar asked Nov 11 '10 13:11

Andrej


People also ask

What does JFrame dispose do?

JFrame. dispose(); causes the JFrame window to be destroyed and cleaned up by the operating system. According to the documentation, this can cause the Java VM to terminate if there are no other Windows available, but this should really just be seen as a side effect rather than the norm.

What does dispose () do in Java?

The Dispose() method The Dispose method performs all object cleanup, so the garbage collector no longer needs to call the objects' Object.


2 Answers

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

like image 114
cbaldan Avatar answered Oct 14 '22 04:10

cbaldan


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.

like image 21
camickr Avatar answered Oct 14 '22 05:10

camickr