我正在关注 this使键绑定(bind)在我的应用程序中工作的指南。到目前为止,当我按下一个键时,键绑定(bind)成功触发。我期望发生的事情是,当我将一个 Action 绑定(bind)到按键按下事件并将另一个 Action 绑定(bind)到按键释放事件时,它将在按下键时触发第一个 Action ,在释放键时触发第二个 Action 。当我按住一个键时实际发生的是两个 Action 都被多次调用。我可以做些什么来实现我想要的行为?
下面是我实现键绑定(bind)的方式:
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
,一切都会按我预期的那样运行。
最佳答案
在 Swing Action 中使用
Boolean
值当一次触发事件然后将Boolean
从false
更改为true
或反之亦然很抱歉没有人知道您是如何实现 KeyBindings 的, 发布 SSCCE
关于java - 按住键时键绑定(bind)会多次触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9850828/