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?
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.
The Dispose() method The Dispose method performs all object cleanup, so the garbage collector no longer needs to call the objects' Object.
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:
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With