Вы можете зарегистрировать обработчик событий в сцене и проверить, имеет ли кнопка фокус:
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();
}
}