mynameisJEFF mynameisJEFF - 1 year ago 168
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

that sits in a
and when it is clicked , it performs a list of tasks. Now I want to bind the
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 Source

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 :

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

      Scene scene = new Scene(root, 0, 0);

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

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