I tried a addWindowListener
and implement the windowClosing
, it works, when I press the close button, but when I use Cmd+Q
to close, the windowClosing
is not being called, how can I solve it? Do I need to detect Cmd+Q
on mac, Alt + F4
on windows via key listener? Is that a general listener for closing window, whatever via the close button or keyboard, or event Ctrl+Alt+Delete
or Cmd+Option+Esc
to focus kill? Thanks.

- 730,956
- 141
- 904
- 1,278

- 29,344
- 50
- 131
- 195
-
2http://stackoverflow.com/questions/2061194/swing-on-osx-how-to-trap-command-q – dacwe Nov 21 '11 at 11:51
-
http://www.leepoint.net/notes-java/GUI/containers/10windows/12frameclose.html – Omid Nazifi Jan 23 '13 at 05:52
-
@TedWong Did you find a solution to your problem? Please post your own answer if you did. – Igor Mar 21 '13 at 11:19
5 Answers
I'm not sure what the situation is on Macs, but on Windows you get the windowClosing() callback from the close button; Alt-F4
; and if you close the app via task manager. You don't get the callback if you use task manager to kill the process, but I wouldn't expect that anyway.
You have remembered to call setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
on your JFrame instance, haven't you?

- 4,315
- 1
- 27
- 33
there is one more method windowClosed() try overriding thing method. hope it will work for you.
-
+1 example http://stackoverflow.com/questions/7613577/java-how-do-i-prevent-windowclosing-from-actually-closing-the-window/7613768#7613768 – mKorbel Nov 21 '11 at 12:28
-
looks like (for me) windowClosing gets called if they hit the X (and windowClosed doesn't), and windowClosed gets called if I programmatically call dispose. Weird. – rogerdpack May 17 '12 at 20:35
You can use this osx library: com.apple.eawt.ApplicationListener
handleQuit(ApplicationEvent event)
Will probably do the trick.
Information from the docs:
Called when the application is sent the Quit event. This event is generated when the user selects Quit from the application menu, when the user types Command-Q, or when the user control clicks on your application icon in the Dock and chooses Quit. You can either accept or reject the request to quit.
Of course this solution will not work on Windows. As far as I know there is however no universal solution, so this is probably the best way to go.

- 682
- 4
- 11
As you said windowClosing is called when you click the (x) button. I am also on a mac and the way I get the CMD+Q to send a signal to the application is using Runtime.addShutDownHook
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
// code to run when CMD+Q is pressed
}
}

- 1
- 2