2013-03-23 124 views
2

我讀過使用KeyBindings比KeyListeners更好。我看到KeyBindings如何對特定鍵的特定反應有用;但我也試圖檢測鍵盤上的任意鍵的按下/釋放:有沒有辦法用KeyBindings來做到這一點?Java - 使用KeyBindings檢測任何按鍵?

例如,我會用一個KeyBinding通常在單一鍵充當這樣:

InputMap iMap = component.getInputMap(); 
ActionMap aMap = component.getActionMap(); 

iMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "enter without modifiers"); 
aMap.put("enter without modifiers", new AbstractAction(){ 
     public void actionPerformed(ActionEvent a){ 
       System.out.println("Enter pressed alone"); 
     }); 

所以我想這樣的檢測按任何鍵:

iMap.put(KeyStroke.getKeyStroke(KeyEvent.KEY_PRESSED, 0), "any key was pressed"); 
aMap.put("any key was pressed", new AbstractAction(){ 
     public void actionPerformed(ActionEvent a){ 
       System.out.println("some key was pressed, regardless of which key..."); 
     }); 

有一種方法來實現這一點?

另外,有沒有辦法讓他們與任何修飾符組合KeyBinding?例如。無論是否存在修飾符,或者如果在任何組合中都同時使用了ctrl-alt等,都會映射Enter-action?

非常感謝, 丹

上跨貼:http://www.javaprogrammingforums.com/whats-wrong-my-code/26194-how-detect-any-key-press-keybindings.html#post103862

+0

此請求已解決.. 您是否在另一個網站上刪除了我的帖子?因爲如果是這種情況,我甚至都不會看到讓我交叉引用它的意義...... – 2013-03-23 19:58:42

+0

現在可見。 – 2013-03-23 20:03:36

+0

我看不到它。 但無論如何,如果你有我的答案,我將不勝感激。 – 2013-03-23 20:07:26

回答

5

我看看鍵綁定怎麼是給特定鍵的特定反應有用的;

是的,那就是當你要使用的鍵綁定

,但我也想檢測鍵盤上的任意鍵的按下/釋放:有沒有辦法用一個KeyBinding做到這一點?

不,密鑰綁定不用於此目的。

另外,有沒有辦法讓他們與任何修飾符組合KeyBinding?

不,再次綁定是針對特定的KeyStroke。所以你需要編寫一個方法爲每個組合添加綁定。請注意訂單無關緊要。即Shift + Alt與Alt + Shift相同

在大多數情況下,鍵綁定是首選方法。在你的情況下,它不是。

如果您正在偵聽具有焦點的特定組件上的KeyEvent,則KeyListener可能是合適的。

或者您想要更全面地聽KeyEvents,那麼您可以看看Global Event Listeners或者Global Event Dispatching,具體取決於您的具體要求。

+0

謝謝, -Daniel – 2013-03-23 20:49:49