我正在按照本指南获取键绑定在我的应用程序中工作.到目前为止,当我按下一个键时,键绑定成功触发.我期望发生的是当我将一个动作绑定到一个键按下事件而另一个动作绑定到一个键释放事件时,它将在按下该键时触发第一个动作,并在释放该键时触发第二个动作.当我按住某个键时实际发生的事情是这两个动作都被多次调用.我能做些什么来实现我想要的行为?
这是我如何实现键绑定:
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);
Run Code Online (Sandbox Code Playgroud)
当我运行程序时,当我按住向上键时实际得到的输出是Pressed UP,稍微暂停,然后是多个Pressed UP值.当我发布up键时,我收到一条Released UP消息.整个输出看起来像这样:
Pressed UP
Pressed UP
Pressed UP
Pressed UP
Pressed UP
Pressed UP
Pressed UP
Released UP
Run Code Online (Sandbox Code Playgroud)
真的很奇怪的是,如果我用键盘字母键替换UP,例如P,一切都按照我的预期运行.
在一次性触发事件时使用Swing Action中的Boolean值,然后 从更改为,反之亦然Booleanfalsetrue
对不起,没人知道你是如何实现KeyBindings的,发布了一个SSCCE