2012-03-24 30 views
3

我正在關注this指南,讓我的應用程序中的密鑰綁定工作。到目前爲止,當我按下某個鍵時,鍵綁定成功啓動。我期望發生的事情是,當我將一個動作綁定到一個按鍵事件並將另一個動作綁定到一個鍵釋放事件時,它將觸發按下鍵時的第一個動作和鍵釋放時的第二個動作。當我按住一個鍵時實際發生的事情都是被多次調用的動作。我能做些什麼來實現我想要的行爲?鑰匙綁定持有密鑰時觸發多次

這裏是我是如何實現的鍵綁定:

component.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("pressed UP"), "pressedUP"); 
component.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("released UP"), "releasedUP"); 

Action pressedUpAction = new AbstractAction() 
{ 
    public void actionPerformed(ActionEvent e) 
    { 
     System.out.println("Pressed UP"); 
    }   
}; 

Action releasedUpAction = new AbstractAction() 
{ 
    public void actionPerformed(ActionEvent e) 
    { 
     System.out.println("Released UP"); 
    }   
}; 

component.getActionMap().put("pressedUP", pressedUpAction); 
component.getActionMap().put("releasedUP", releasedUpAction); 

當我運行該程序,輸出其實我時,我按住拿到了關鍵的是Pressed UP,輕微的停頓,然後多Pressed UP值。當我釋放向上密鑰時,我收到一條Released UP消息。整個看起來就像這樣:

Pressed UP 
Pressed UP 
Pressed UP 
Pressed UP 
Pressed UP 
Pressed UP 
Pressed UP 
Released UP 

真正奇怪的是,如果我用鍵盤字母鍵更換UP,如P,一切正常,我希望它。

回答

7
  • 使用Boolean值內Swing Action當一次次觸發的事件,然後從false改變Booleantrue反之亦然

  • 對不起,沒人知道你是怎麼實現的KeyBindings,張貼SSCCE

+2

一個動作已經_has_一個適合在這裏使用的布爾值:它叫做_enabled_ :-) – kleopatra 2012-03-24 10:34:18

+0

ahhhh,很棒的m inds認爲是一樣的,感謝上課 – mKorbel 2012-03-24 10:39:18

+0

對不起,我第一次打字時很匆忙。我現在會發布SSCCE。 – LandonSchropp 2012-03-24 21:59:51