Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
812 views
in Technique[技术] by (71.8m points)

java - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...