javalibgdxkeycodekeyboard-layoutdvorak

Convert libgdx int keycode to non-QWERTY char


I've got a bunch of code set up that uses InputListener.keyDown to test keys pressed, and uses those keycodes to display keystroke hints. However, on non-QWERTY keyboard layouts (like Dvorak or Colemak), getting those keycodes via Input.Keys.toString(keycode) doesn't return the actual character that would be displayed by pressing the key. (For example, pressing the 'E' key on my QWERTY-hardware keyboard will always return the keycode for 'E', rather than returning the keycode for 'F' when I'm using a Colemak keyboard layout)

Is there a way to use a keycode to get the actual value that would be typed when pressing that key?

Using keyTyped gives me the correct character value, but switching all the code from keyDown to keyTyped would be a hefty refactor.


Solution

  • Fixed! I ended up using GLFW.glfwGetKeyName and DefaultLwjgl3Input.getGlfwKeyCode to get the keyname where possible, and falling back to just using Input.Keys.toString in other cases (specifically, non-alphanumeric keys)

    String keyName = GLFW.glfwGetKeyName(DefaultLwjgl3Input.getGlfwKeyCode(keystroke), 0);
    if(keyName != null && !keyName.equals("")) {
        return keyName.toUpperCase();
    }
    return Input.Keys.toString(keystroke);
    

    It's worth noting that this is specific to the LWJGL3 backend. LWJGL3 uses the physical keyboard layout (so if you use keyDown to check for WASD, on an AZERTY keyboard layout it'll check for ZQSD, the keys in the same location), while LWJGL2 uses the localized keys.