Search code examples
javajavafxcontrollerjavafx-8fxml

JavaFX Is there any better way to get keycode of Question Mark and others


Is there any better way to get keycodes of these ()<>?:"{}|!@#$%^&* as a string for a method without this long process JavaFX

I first check if the shift is pressed if yes .getCode() and if that keyCOde = SLASH then use "?" question mark. But this is pretty long

scene.setOnKeyPressed(new EventHandler<KeyEvent>() {

                @Override
                public void handle(KeyEvent e) {                


                    if(e.isShiftDown()) {


                        switch (e.getCode()) {

                        case SLASH:                     
                            bot_list.get(0).hit("?");   
                            break;

                        case LEFT_PARENTHESIS:                          
                            bot_list.get(0).hit(",");
                            break;

                        case RIGHT_PARENTHESIS:                     
                            bot_list.get(0).hit(".");
                            break;

                        case QUOTE:
                            bot_list.get(0).hit("'");
                            break;

                        case SEMICOLON:
                            bot_list.get(0).hit(":");
                            break;

                        case BRACELEFT:
                            bot_list.get(0).hit("{");
                            break;

                        case BRACERIGHT:
                            bot_list.get(0).hit("}");
                            break;

                        case OPEN_BRACKET:
                            bot_list.get(0).hit("[");
                            break;

                        case CLOSE_BRACKET:
                            bot_list.get(0).hit("]");
                            break;

                        case BACK_SLASH:
                            bot_list.get(0).hit("|");
                            break;

                        case BACK_QUOTE:
                            bot_list.get(0).hit("~");
                            break;


                    }
                    }

Solution

  • If you're willing to use the KEY_TYPED event instead, you can get the output using the KeyEvent.character property:

    targetNode.setOnKeyTyped(evt -> {
        System.out.println(evt.getCharacter());
    });
    

    On the other hand you cannot use KeyEvent.code from KEY_TYPED events.