Search code examples
javafxjavafx-css

How do you make ENTER trigger onAction for JavaFX globally?


I saw in another question that this was the solution for when you want to press enter to trigger onAction

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

Is there a way to do this globally for all buttons, or will I have to initialize each component and go through every button and bind it this way?


Solution

  • You can register an event handler with the scene, and check if a button has focus:

    Scene scene = ... ;
    scene.addEventHandler(KeyEvent.KEY_PRESSED, e -> {
        if (e.getCode() == KeyCode.ENTER) {
            if (scene.getFocusOwner() instanceof Button) {
                Button button = (Button)scene.getFocusOwner();
                button.fire();
            }
        }
    });
    

    Demo:

    import javafx.application.Application;
    import javafx.scene.Scene;
    import javafx.scene.control.Button;
    import javafx.scene.control.TextField;
    import javafx.scene.input.KeyCode;
    import javafx.scene.input.KeyEvent;
    import javafx.scene.layout.HBox;
    import javafx.stage.Stage;
    
    public class App extends Application {
    
        @Override
        public void start(Stage stage) {
    
            HBox controls = new HBox(5);
            controls.getChildren().add(new TextField());
            for (int i = 1 ; i <=5 ; i++) {
                String text = "Button "+i ;
                Button button = new Button(text);
                button.setOnAction(e -> System.out.println(text));
                controls.getChildren().add(button);
            }
    
            Scene scene = new Scene(controls, 600, 400);
            scene.addEventHandler(KeyEvent.KEY_PRESSED, e -> {
                if (e.getCode() == KeyCode.ENTER) {
                    if (scene.getFocusOwner() instanceof Button) {
                        Button button = (Button) scene.getFocusOwner();
                        button.fire();
                    }
                }
            });
    
    
            stage.setScene(scene);
            stage.show();
        }
    
        public static void main(String[] args) {
            launch();
        }
    
    }