6

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.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
DNB5brims
  • 29,344
  • 50
  • 131
  • 195

5 Answers5

2

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?

vaughandroid
  • 4,315
  • 1
  • 27
  • 33
2

there is one more method windowClosed() try overriding thing method. hope it will work for you.

mKorbel
  • 109,525
  • 20
  • 134
  • 319
gprathour
  • 14,813
  • 5
  • 66
  • 90
  • +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
1

Sounds like you need to add some KeyListeners and a factory to detect the one you want for a particular operating system.

Check Out

gprathour
  • 14,813
  • 5
  • 66
  • 90
duffymo
  • 305,152
  • 44
  • 369
  • 561
1

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.

Aloys
  • 682
  • 4
  • 11
0

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
    }
}
Daniel V
  • 1
  • 2