I’ve got a game where I’m trying to intercept a close event and return the user to the main menu instead. I’ve got half of it figured out using DO_NOTHING_ON_CLOSE but then the problem is I can’t return the regular functionality to the menu screen.
As you probably know, the problem is, the windowClosing method is apparently the last listener fired if DO_NOTHING... is the operation.
So, my question is, how can I return the EXIT_ON_CLOSE to the window, after NOTHING has been done? I’d like to do it without any user input in the meantime. I can switch to another JFrame and handle it from there, but there’s got to be a better way to do it.
Code sample:
WindowAdapter waReturnToMenu = new WindowAdapter() {
@Override
public void windowClosing(final WindowEvent e) {
view.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
changeMenuState(0);
}
};
Then, in change menu state:
public void changeMenuState(int i0) {
//...screen returns to menu, then
view.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
Why not include this logic in your WindowListener since this will be called when closing is ever attempted? Your code sets the state of a boolean variable to tell the WindowListener if you wish it to return the user to the program or close the program. In the WindowListener you would check the state of this boolean variable, and if the state is a certain value, exit the program via
System.exit(...).(made into an answer)
e.g.,
Then, in change menu state: