1

So I have this button on my stage:

    @FXML

public void generateButton(ActionEvent event) {

    String fingerprint = fingerprintText.getText().toLowerCase();
    String erg = Verifier.getDdProUnlockPIN(fingerprint);
    pinField.setText(erg);
    copyText = erg;
    log.info("Pin " + erg + "wird generiert");
}

Now I want it to be triggered when the Enter Key is being pressed, but how?

kinansaeb
  • 43
  • 1
  • 2
  • 7
  • Related: [Using JavaFX 2.2 Mnemonic](http://stackoverflow.com/questions/12710468/using-javafx-2-2-mnemonic). Note that the related answer talks about an Accelerator rather than a mnemonic. Accelerators are good for generating actions based upon general key combinations, though I don't know that it would be a great idea to have an accelerator for the enter key as the enter key is also used for new lines in multiline text fields and I don't know how an enter key accelerator would behave in such a case. – jewelsea Apr 04 '17 at 06:54

1 Answers1

2

Fist, set a hanlder on your button :

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

If the button has the focus, pressing Enter will automatically call this handler. Otherwise, you can do this in you 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) {
           myButton.fire();
           ev.consume(); 
        }
    });

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

myButton.setDefaultButton(true);
Jay Smith
  • 2,331
  • 3
  • 16
  • 27
  • http://stackoverflow.com/questions/32038418/javafx-how-to-bind-the-enter-key-to-a-button-and-fire-off-an-event-when-it-is-c – kinansaeb Apr 04 '17 at 06:32
  • "If the button has the focus, pressing Enter will automatically call this handler." <- Actually, on OS X at least, that doesn't occur. Pressing space will fire the action handler of a focused button, but Enter will not (unless it is a default button or a scene level event handler, filter or accelerator for the enter key is setup). – jewelsea Apr 04 '17 at 06:50