Is there a way to convert a key code into the character that goes with it? It needs to be like KeyEvent.getKeyChar(), but not require a KeyEvent object.
If you just want the keycode name (for example “VK_A”) associated with a given keycode value, you can use reflection on the KeyEvent class to retrieve this information.
If on the other hand you want to convert a keycode into a character, then you will soon realize this is impossible as it is not a one-to-one relationship.
Keycodes relate to the physical keys on the keyboard - as such some generate no character (e.g. ALT), while others generate many different characters (depending upon the state of the shift/alt/control keys & num/func/caps lock keys).
What about KeyEvent.getKeyText(int keyCode)
But for symbols that returns stuff like “Equals” and “Left Bracket”; I need the actual character.
I’m not actually going to display the character, so modifier keys don’t matter. The game has Lua scripting so I want to give the user something more friendly than the code to work with.
I suppose I could just make an empty hashtable of key codes/characters and add values to it in my key event handler.
Take a look at the source of KeyEvent (Codesearch) line 549:
this(src, id, when, modifiers, keyCode,
(keyCode > (2 << 7) - 1) ? CHAR_UNDEFINED : (char) keyCode);
looks like the keyCode simply is the ASCI char for codes < 127 (which is the result of (2 << 7) - 1) - seems like someone had his funny day when writing this code…), so just cast it to (char) and you are done.