I am making a distributed concurrent game online using Java and Swing. I want to remove the player's icon from the game zone when the user press the [x] to close the window. How can i say to the VM to execute a function before terminating the process?
-
Any attempts? Any code you can provide? – Cath Jul 07 '17 at 14:40
2 Answers
Assuming you are using a JFrame
, set its default close operation do DO_NOTHING_ON_CLOSE
and add a WindowListener
to react on windowClosing
.
This method can do what ever is needed and then just dispose
the window to actually close it.
Note: this can also be used to ask the user if she/he really wants to exit...

- 28,957
- 10
- 64
- 87
If you're using a JFrame, I think you should better write your own KeyEventDispatcher like described in that post: Unresponsive KeyListener for JFrame If you're just adding a KeyListener to a JFrame and you have selectable components placed on it, you have to add the listener to all these components too, presumably recursively.
You can then detect when somebody presses x and then call the dispose function of the JFrame. If you're also adding a WindowListener to your JFrame, you can put some code in the windowClosing method that is called before the frame closes.

- 356
- 2
- 13