Reputation: 391
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?
Upvotes: 11
Views: 20268
Reputation: 34403
If you want to catch dispose
reliably, no matter how it is called, you can override the dispose
method. Usually you want to call super.dispose()
and implement any custom handling before or after it as suitable for given task.
JFrame frame = new JFrame("FrameDemo") {
@Override
public void dispose() {
System.out.println("On dispose");
super.dispose();
}
};
Upvotes: 1
Reputation: 553
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
}
});
Upvotes: 13
Reputation: 324118
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.
Upvotes: 3