mynameisJEFF mynameisJEFF - 2 months ago 29
Java Question

javafx: How to bind the Enter key to a button and fire off an event when it is clicked?

Basically, I have a

okayButton
that sits in a
stage
and when it is clicked , it performs a list of tasks. Now I want to bind the
Enter
key to this button such that when it is clicked OR the ENTER key is pressed, it performs a list of tasks.

okayButton.setOnAction(e -> {
.........
}
});


How can I do that ? I have read the following post already. However, it did not help me to achieve what I want to do.

Answer

Fist, set a hanlder on your button :

okayButton.setOnAction(e -> {       
       ......
});

If the button has the focus, pressing Enter will automatically call this handler. Otherwise, you can do this in you startmethod :

@Override
public void start(Stage primaryStage) {
      // ...
      Node root = ...;
      setGlobalEventHandler(root);

      Scene scene = new Scene(root, 0, 0);
      primaryStage.setScene(scene);
      primaryStage.show();
}

private void setGlobalEventHandler(Node root) {
    root.addEventHandler(KeyEvent.KEY_PRESSED, ev -> {
        if (ev.getCode() == KeyCode.ENTER) {
           okayButton.fire();
           ev.consume(); 
        }
    });
}

If you have only one button of this kind, you can use instead

okayButton.setDefaultButton(true);