I have a question about the relationship between swing window listener and default close operation. The question occurs when I am dealing with below scenario:
I add a window listener (WindowAdapter
is used for the listener) for a JFrame
, and override the windowClosing
function: if the user closes the window, a dialog will pop up to confirm, if user chooses CANCEL
option, then directly return. However, when I test the code and choose CANCEL
when closing the window, the frame window is still closed (or maybe just invisible, because the Java icon is still in the task bar).
Then I add the default close option with DO_NOTHING_ON_CLOSE
, with the same test behavior, the frame window is not closed, which is what I expected.
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
Then I change the default close option with EXIT_ON_CLOSE
, with the same test behavior, the frame window is directly closed(this time Java icon also disappeared).
This makes me confused. Does it mean the window listener can just define what to do when the window is closing but can't determine whether to close the window? Or I need to override other function?
The window listener is just a listener. It does not affect the default close operation, unless you actually change the default close operation in the windowClosing() code.
I use:
frame.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
as the default when the frame is created. Then in the windowClosing(...)
method, if the user confirms the closing of the frame I change the default:
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
Check out Closing an Application for more information and more complete example code.