Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

javafx

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.

like image 382
mynameisJEFF Avatar asked Aug 16 '15 18:08

mynameisJEFF


3 Answers

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);
like image 136
Dici Avatar answered Oct 11 '22 11:10

Dici


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

btn.defaultButtonProperty().bind(btn.focusedProperty());
like image 31
Abdul.Moqueet Avatar answered Oct 11 '22 09:10

Abdul.Moqueet


I've had the same problem like mynameisJEFF. (I'm using Windows and as I read here: http://mail.openjdk.java.net/pipermail/openjfx-dev/2016-June/019234.html it is the SPACE_BAR and not ENTER, which fires a Button in JavaFX) I didn't want to add a listener to every Button, so I registered a Listener to the root node and asked the scene, which node is focused to fire that one. Here is my code (it is xtend, but I think it very easy to understand):

override start(Stage primaryStage) throws Exception {
    val root = FXTable.createRoot
    val mainScene = new Scene(root)
    root.addEventHandler(KeyEvent.KEY_RELEASED, [event|
        if(event.code === KeyCode.ENTER){
            switch(focusedNode : mainScene.focusOwnerProperty.get){
                Button:{
                    focusedNode.fire
                    event.consume
                }
                default:{
                }
            }
        }
    ])
    primaryStage.scene = mainScene
    primaryStage.show
    primaryStage.maximized = true
}
like image 1
armin.miedl Avatar answered Oct 11 '22 10:10

armin.miedl