0

In my program want to have a text field that will contain the current keys pressed by the user. I can do this with JNativeHook, but the problem currently is that JNativeHook is registering tons of key presses when it is held down. Is there a way to ignore key holds? I would like to simply append to the text field whatever keys are currently held without overpopulating it with duplicates

Here is the relevant part of my code: (This is in my main class that extends Application and implements NativeKeyListener)

@Override
public void nativeKeyPressed(NativeKeyEvent e) {
    System.out.print(NativeKeyEvent.getKeyText(e.getKeyCode()) + " + ");

    if (e.getKeyText(e.getKeyCode()) == "F6")
        System.out.println("F6");


}
@Override
public void nativeKeyReleased(NativeKeyEvent e) {
    try {
        GlobalScreen.unregisterNativeHook();
    } catch (NativeHookException ex) {}
}
@Override
public void nativeKeyTyped(NativeKeyEvent e) {

}

All of this works fine, but if I hold a key, it will spam that key code in the console. Can I stop this?

4

1 回答 1

1

只需将您的代码移至 nativeKeyTyped。每次按下并释放一个键时,它只会触发一次。

按下的键将在初始单击时触发,然后在正常单击和按住键之间超时后,它将在每次更新时给出按下键的更新。

如果你想要更多的控制权,你可以添加一张地图。此示例使用 hashmap 来记录是否正在按下某个键以及它应该等待多少更新直到再次触发。不过,我并没有完全看 api,所以如果某些函数调用输入错误,我不会感到惊讶。

private Map<Integer, Integer> keysHeld = new Hashmap();


@Override
public void nativeKeyPressed(NativeKeyEvent e) {
    //When the countdown gets to 0, do a key update
    if (keysHeld.getOrDefault(e.keyCode(), 0) <= 0) {
        //Do whatever you want to do.

        //Set the countdown again, so it can be activated again after a reasonable amount of time.
        keysHeld.put(e.keyCode(), 50);
    }

    //Decrease the countdown by 1 each update until it triggers or is released.
    keysHeld.put(e.keyCode(), e.getOrDefault(e.keyCode(), 50) - 1);
}

 @Override
 public void nativeKeyReleased(NativeKeyEvent e) {
     //Reset countdown when key is released.
     keysHeld.put(e.keyCode(), 0);
}
于 2018-08-21T08:32:34.780 回答