0

I'm making a video game with a simple inventory system. I'm trying to make it so that whenever you press the "Z" key it would show or hide the inventory GUI. I don't know why, but the KEY_TYPED key events aren't working. The KEY_PRESSED and KEY_RELEASED key events are working perfectly fine.

Here is my key event handler class:

public static KeyCode handle(javafx.scene.input.KeyEvent e) {
    if (e.getEventType() == javafx.scene.input.KeyEvent.KEY_PRESSED) {
        e.consume();
        return e.getCode();
    }

    if (e.getEventType() == javafx.scene.input.KeyEvent.KEY_RELEASED) {
        e.consume();
        return e.getCode();
    }

    if (e.getEventType() == javafx.scene.input.KeyEvent.KEY_TYPED) {
        e.consume();
        return e.getCode();
    }

    return null;
}

Here is where I'm using the key events:

    primaryStage.getScene().setOnKeyTyped(event -> {
        KeyCode e = KeyEvent.handle(event);

        if (e == KeyCode.Z) {
            System.out.println("test");
        }
    });

When I tried pressing the key, it did absolutely nothing.

Superhuman
  • 85
  • 9
  • Use `KEY_TYPED` events when the user is typing into some kind of text input control. If you need to do an action based on a key, use `KEY_PRESSED`. Also, I'm not understanding the purpose of your `handle(KeyEvent)` method. – Slaw Jun 09 '19 at 15:57
  • A key-typed event is the result of one or more key-pressed and/or key-released events. If you consume those, you are probably preventing key-typed events from occurring. Is there any actual benefit to consuming the key events? (Also, naming your own class `KeyEvent` seems like a bad idea that will lead to confusion. Perhaps `KeyEventHandler` would be better?) – VGR Jun 09 '19 at 16:13
  • Oh I thought that `KEY_TYPED` was the result of when someone presses and released a key. I guess I should use `KEY_RELEASED` right? – Superhuman Jun 09 '19 at 20:18

1 Answers1

3

On a KEY_TYPED event you extract the code from the event and return it from your handler, and later compare it to KeyCode.Z.

The API Doc for KeyEvent states:

For key pressed and key released events, the code variable contains the event's key code. For key typed events, the code variable always contains KeyCode.UNDEFINED.

So you are comparing KeyCode.UNDEFINED to KeyCode.Z which will not match.

You will have to use KeyEvent.getCharacter() in case of a key typed event and compare that to "Z"

P.J.Meisch
  • 18,013
  • 6
  • 50
  • 66