java - 按住键时键绑定(bind)会多次触发

标签 java swing

我正在关注 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 值当一次触发事件然后将 Booleanfalse 更改为 true 或反之亦然

  • 很抱歉没有人知道您是如何实现 KeyBindings 的, 发布 SSCCE

关于java - 按住键时键绑定(bind)会多次触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9850828/

相关文章:

java - 使用 Java 的 runtime.exec 进行 Shell (bash) 大括号扩展

java - jtable 中删除具有相同值的多行

java - setBackground 不适用于小程序背景

java - 使用 JLabel 和 ArrayList 中的 java 变量的新行

java - 在 Tomcat 中进行开发的最佳 IDE 是什么?

java - 我们可以将字符串格式的日期 dd/mm/yyyy 转换为相同格式的日期时间吗?

java - 如何在 UIManager 中使用默认的 Nimbus 颜色?

swing - 如何将 javax.mail.Session setDebug 重定向到 jTextArea

java - JIT C2 方法最大大小

java - Hibernate 中 key '0' 的重复条目 'PRIMARY'