How to detect JFrame closed?

I tried addWindowListener and implemented windowClosing , it works when I click the close button, but when I use Cmd+Q to close, windowClosing not called, how can I solve it? Do I need to detect Cmd+Q on mac, Alt + F4 on windows through a key listener? Is this a regular listener to close a window, regardless of the close button or keyboard, or the Ctrl+Alt+Delete or Cmd+Option+Esc events to focus the kill? Thanks.

+6
source share
5 answers

I'm not sure what the situation is on a Mac, but on Windows you get a windowClosing () callback from the close button; Alt-F4 ; and if you close the application through the task manager. You will not receive a callback if you use the task manager to kill the process, but I would not expect this.

You remembered that you were calling setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); to your JFrame instance, right?

+2
source

there is another windowClosed () method, try overriding the method. hope this works for you.

+2
source

It looks like you need to add some KeyListeners and factory to find the one you want for a specific operating system.

Departure

+1
source

You can use this osx library: com.apple.eawt.ApplicationListener

 handleQuit(ApplicationEvent event) 

Probably this trick.

Information from the documents:

Invoked when an application dispatches a 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 the icon of your application in the Dock and selects Quit. You can accept or decline the exit request.

Of course, this solution will not work on Windows. As far as I know, there is no universal solution, so this is probably the best way.

+1
source

As you said, windowClosing is called when you press the (x) button. I am also on mac and as I get CMD + Q to send a signal to the application, use Runtime.addShutDownHook

 Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { // code to run when CMD+Q is pressed } } 
0
source

Source: https://habr.com/ru/post/901994/


All Articles