【问题标题】:How do you make ENTER trigger onAction for JavaFX globally?你如何让 ENTER 在全球范围内触发 JavaFX 的 onAction?
【发布时间】:2020-10-07 19:40:05
【问题描述】:

我在另一个问题中看到,这是当您想按 Enter 触发 onAction 时的解决方案

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

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

【问题讨论】:

  • 不确定是否可以有多个默认按钮。在 Javadoc 中,听起来应该最多有一个这样的按钮(至少根据单数的使用来判断)......
  • 不特定于特定版本的 fx,已删除标签..

标签: javafx javafx-css


【解决方案1】:

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

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

}

【讨论】:

  • 这非常适合我的需要,谢谢。
猜你喜欢
  • 2014-11-03
  • 2014-11-22
  • 1970-01-01
  • 2017-03-26
  • 2020-07-11
  • 2021-09-07
  • 1970-01-01
  • 1970-01-01
  • 2016-07-03
相关资源
最近更新 更多