How to convert KeyCode to text.

I’m making a key control options. I save my keys as KeyCode’s but how to I convert this to string?
toString() gives me “VK_A” for A, which I only want ‘A’.

You should have access to the KeyEvent object, from which you can get either the key code (int) or the key char (char).

From the javadocs:

char getKeyChar()
Returns the character associated with the key in this event.

int getKeyCode()
Returns the integer keyCode associated with the key in this event.

KeyEvent.getKeyText(int keyCode);
KeyEvent.getKeyModifiersText(int modifiers);

Those methods don’t seem to be in JavaFX. I don’t want to use Java otherwise it won’t be portable.

http://java.sun.com/javafx/1.2/docs/api/javafx.scene.input/javafx.scene.input.KeyEvent.html

Note the ‘text’ field.

Yes I know that, but I’m working with KeyCode’s not KeyEvent’s.
Is it possible to convert a Keycode back into a KeyEvent?

What I’m doing is making custom controls and on load up I create my own default KeyCodes and then if the user wants too, they can over write them to there liking.

this is how we did it in darkchat (maybe a better way).

first do a onKeyPressed on your node:


onKeyPressed: function(e:KeyEvent):Void {
      handleKeyInput(e.code.toString().trim());
}

then do a onKeyTyped on the same node:


onKeyTyped: function(e:KeyEvent):Void {
      handleKeyInput(e.char.toString().trim());
}

then call a function to work out if it was a code or a char:


function handleKeyInput( keyInput ) {
       if ( keyInput.length() == 1 ) { 
             // it is a char
             ....
       } else {
             // it is a keycode
             ....
             if ( keyInput == "VK_BACK_SPACE") {
                    ....
             }
       }
}

bit hackie imo, but what can you do?

Might just toString() the KeyCode and remove the “VK_” at the front and convert to lower case and swap the underscore for spaces. That would make it fine, and if it doesn’t well too bad! heh

There should be a KeyEvent.getKeyText(int keyCode) in JavaFX. Would make things a lot easier.

Edit: Heres the code.

public function KeyCodeString(k:KeyCode):String{
    var s:String = k.toString();
    if(s.startsWith("VK_")){
        s = s.substring(3, s.length());
    }
    s = s.replace("_", " ");

    return s;
}