您如何使 ENTER 全局触发 JavaFX 的 onAction?

How do you make ENTER trigger onAction for JavaFX globally?

我在另一个问题中看到这是当你想按回车来触发 onAction 时的解决方案

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

有没有办法为所有按钮全局执行此操作,或者我是否必须初始化每个组件并遍历每个按钮并以这种方式绑定它?

您可以在场景中注册一个事件处理程序,并检查按钮是否有焦点:

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

演示:

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

}