Java KeyEvent注册未被按下的键

时间:2019-06-04 22:11:07

标签: java keyevent

我想要一个程序,该程序将使用KeyEvent读取一个文件中按下的键,然后在下一个文件中将其写入控制台。我已经设置了Q&W键,但是每当我尝试运行该程序时,它都会向“ Key Q Pressed”和“ Key W Pressed”发送垃圾邮件。

我尝试将KeyPressed更改为KeyTyped,什么也没有。 KeyPressed,KeyTyped和KeyReleased的单独功能,什么也没有。删除CHAR_UNDEFINED,什么也没有。

主要IsKeyPressed.java

import java.awt.KeyEventDispatcher;
import java.awt.KeyboardFocusManager;
import java.awt.event.KeyEvent;

public class IsKeyPressed {
    private static volatile boolean qPressed = false;
    private static volatile boolean wPressed = false;

    public static boolean isQPressed() {
        synchronized (IsKeyPressed.class) {
            return qPressed;
        }
    }

    public static boolean isWPressed() {
        synchronized (IsKeyPressed.class) {
            return wPressed;
        }
    }

    public static void main(String[] args) {
        KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(new KeyEventDispatcher() {

            @Override
            public boolean dispatchKeyEvent(KeyEvent ke) {
                synchronized (IsKeyPressed.class) {
                    switch(ke.getID()) {
                    case KeyEvent.KEY_PRESSED:
                        if (ke.getKeyCode() == KeyEvent.VK_W) {
                            wPressed = true;
                        } else if (ke.getKeyCode() == KeyEvent.VK_Q) {
                            qPressed = true;
                        }
                        break;

                    case KeyEvent.KEY_RELEASED:
                        if (ke.getKeyCode() == KeyEvent.VK_W) {
                            wPressed = false;
                        } else if (ke.getKeyCode() == KeyEvent.VK_Q) {
                            qPressed = false;
                        }
                        break;
                    }
                    return false;
                }
            }
        });
    }

    public void keyTyped(KeyEvent ke) {
        //test
    }

    public void keyPressed(KeyEvent ke) {
        //test
    }

    public void keyReleased(KeyEvent ke) {
        //test
    }
}

Test.java中的公共类

static boolean randomVariableName = true;

    public static void main(String[] args) {
        while (randomVariableName == true) {
            if (IsKeyPressed.isWPressed()); {
                System.out.println("keydown.W");
            }
            if (IsKeyPressed.isQPressed()); {
                System.out.println("keydown.Q");
            }
        }
    }

我希望在键盘上按Q可以使控制台打印keydown.Q,但是只会显示垃圾邮件keydown.Qkeydown.W

1 个答案:

答案 0 :(得分:2)

以下操作会使您的代码成为垃圾邮件:

 if (IsKeyPressed.isWPressed()); {
     System.out.println("keydown.W");
 }

isWPressed()之后的分号会终止表达式,因此始终为true ...

没有垃圾邮件:

 if (IsKeyPressed.isWPressed()) {
     System.out.println("keydown.W");
 }

此外,我认为您将无法通过KeyboardFocusManager获取键。 至少您必须启动Swing JFrame或AWT窗口才能获取事件。为此,您还可以简单地向组件(例如JTextField)添加键侦听器或键映射

在您自己的应用程序之外获取事件是-恕我直言-使用Java无法实现。