Search code examples
javajavafxjavafx-8fxml

how to use key on pressed in java FXML?I want to use shortcut keys to do button action


I want to use shortcut keys to do action.

<Button layoutX="554.0" layoutY="411.0" mnemonicParsing="false" onAction="#edit" onKeyPressed="#edit_key" prefHeight="27.0" prefWidth="89.0" text="Edit" />

FXML code

@FXML
private void edit_key(KeyEvent event) {
        if (event.getCode() == KeyCode.ENTER) {
        //to do button action               
        }

}

Solution

  • Here is and example to capture a Key Press on a modal form
    In the FXML Editor under the Code section set onKeyPressed="#onPress" our base container is an Anchor Pane. Now in the Controller Class for that Anchor Pane use this method

        @FXML
    private void onPress(KeyEvent ev) throws IOException{
        kc = ev.getCode();
        if(kc == KeyCode.ESCAPE){
            strTRANSFER = txtEnterValue.getText();
            onBack();
        }   
    }
    

    You can use what ever KeyCode you like