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

First, 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 your start method :

@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 the following method instead.

okayButton.setDefaultButton(true);

You can dynamically change the default button property of the currently focused button by using binding

btn.defaultButtonProperty().bind(btn.focusedProperty());

Tags:

Java

Javafx