0

I have a button on a Scene, that whenever the space bar or enter key is pressed, this button automatically fires. I want the user to be able to type these keys without this button firing. I have already tried doing root.requestFocus() and calling the request focus method on other nodes in my scene. How can I prevent this button from firing when these keys are pressed. Thanks for any help.

Edit: So far I have just done the boiler plate code to make a Javafx application work, added that button and a few labels. I have tried the requestFocus() method in several nodes in my application, none of which has made a difference. I also have a scene.setOnKeyPressed action event listener for keys pressed.

4

3 回答 3

5

您可以使用该button.setFocusTraversable()方法(docs)。这可以防止按钮自动聚焦,例如通过按TAB

Button button = new Button("Some Action");
button.setFocusTraversable(false);
button.setOnAction(event -> System.out.println("Some action called!"));
于 2019-03-10T21:58:14.387 回答
3

您是否尝试过添加一个事件过滤器来javafx.scene.input.KeyEvent消耗该事件

于 2019-03-10T21:39:43.517 回答
0

假设您defaultFocusNode有焦点,并且您不希望您在单击时button执行其默认行为,即为自己(和远离defaultFocusNode)焦点button。当button获得焦点时,此代码将立即将焦点返回给defaultFocusNode.

button.focusedProperty().addListener((observableValue, oldValue, newValue) -> {
        if (newValue)  defaultFocusNode.requestFocus();
      });
于 2021-04-29T05:26:01.790 回答