【问题标题】:Key Bindings Fire Multiple Times when Holding Key按住键时键绑定会触发多次
【发布时间】: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,一切都会按我的预期工作。

【问题讨论】:

    标签: java swing


    【解决方案1】:
    • 当一次触发事件时在Swing Action 中使用Boolean 值,然后将Booleanfalse 更改为true,反之亦然

    • 很抱歉没人知道你是怎么实现KeyBindings的,发个SSCCE

    【讨论】:

    • 一个Action已经一个适合在这里使用的布尔值:它被称为enabled :-)
    • 对不起,我第一次打字的时候很着急。我现在就发布 SSCCE。
    • 我现在明白你所说的布尔变量是什么意思了。我误解了键盘事件的工作原理。感谢您的帮助。
    猜你喜欢
    • 2016-03-11
    • 1970-01-01
    • 2013-11-12
    • 2013-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多