【发布时间】:2012-03-25 06:08:03
【问题描述】:
我正在关注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,一切都会按我的预期工作。
【问题讨论】: