Workaround for non-compliant JVM not sending WindowClosing events

拥有回忆 提交于 2019-12-25 03:08:54

问题


Apple JVM on various OS X version have apparently been broken in that they do not generate the WindowClosing event when they should (for example if you close an app's main JFrame using by clicking on the close button).

(in the most recent Apple Java updates you can set a property forcing the event to be generated but this is not what I'm looking for)

My problem is simple: I'd like to display a "tip" when the user closes the app. However I cannot (due to the fact that no event is generated) detected that the user closed the window.

So I thought I could use a shutdown hook:

Runtime.getRuntime().addShutdownHook(...)

However apparently creating a JFrame from a shutdown hook seems problematic: it's like if the EDT was already gone once the shutdown hook is called.

I tried several things and nothing really seems to makes sense: like my "Tip" JFrame staying all gray (despite it working fine when called from anywhere but the shutdown hook) or the program exiting immediately. I tried using a latch and waiting on the latch from the shutdown hook but it's as if the EDT wasn't there anymore.

I'm currently seriously considering spawning a second Java app just to display the tooltip as a workaround but I think it's a bit overkill (but at least it would work).

Did anyone ever try to create a window from a shutdown hook and invoke things on the EDT and are there any gotchas to be aware of? (remember that I cannot reliably catch the window closing events on OS X due to known very-longstanding Apple VM bugs).


回答1:


If the window is actually closing and the application is stopping then something is calling the JFrame.dispose() method. overwrite this, and add your code there.

otherwise you can add a daemon thread that listens to the closed method on the window listener, the daemon can add the tooltip and then dispose of the window. you can delay the dispose until the tooltip is done.

I've never heard of this bug, but things can only get better now that apple isnt releasing its own jdk's.



来源:https://stackoverflow.com/questions/7748882/workaround-for-non-compliant-jvm-not-sending-windowclosing-events

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!