2012-03-24 83 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