开发者

writing global listener

I want the active window (i.e JFrame ot JDialog) to receive specific keyEvent so that whereever the focusing this keyevent is handling by the window such as ALT+F4 if you press it wherever the focusing the active window will close,I try t开发者_Python百科o override postprocesskeyEvent but it doesn't work fine


You can add a global event listener to you application using the addAWTEventListener() method in java.awt.Toolkit.

http://java.sun.com/javase/6/docs/api/java/awt/Toolkit.html#addAWTEventListener%28java.awt.event.AWTEventListener,%20long%29

You will need to choose which type of events you want to receive with the event mask when you add the listener.

For example:

// Then on startup register.
AWTEventListener myGlobalKeyListener = new MyGlobalKeyListener();

Toolkey.getDefaultToolkit().addAWTEventListener(myGlobalKeyListener, AWTEvent.KEY_EVENT_MASK);

If you are trying to stop windows from shutting down your application when the user presses ALT-F4 then an event handler will not help you. I belive the operating system handles this by sending SIGTERM to the application. Java does not receive the KeyEvent for this.


The standard approach for intercepting KeyStrokes when using Swing is to use Key Bindings. Although as mentioned earlier this still won't work for Alt+F4.

If you are trying to prevent Alt+F4 from closing the window, then you need to use the setDefaltCloseOperation(...) method to do nothing. Closing an Application gives more information on this approach.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜