1

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.

Gabe
  • 5,643
  • 3
  • 26
  • 54
  • 1
    Can you share what you have done so far? A [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve). – Samuel Philipp Mar 10 '19 at 21:25

3 Answers3

6

You can use the button.setFocusTraversable() method (docs). This prevents the button from being focused automatically, e.g. by pressing TAB.

Button button = new Button("Some Action");
button.setFocusTraversable(false);
button.setOnAction(event -> System.out.println("Some action called!"));
Samuel Philipp
  • 10,631
  • 12
  • 36
  • 56
5

Have you tried adding an event filter for javafx.scene.input.KeyEvent that consumes the event?

0

Say your defaultFocusNode has focus, and you don't want your button to do its default behavior of taking focus for itself (and away from defaultFocusNode) when button is clicked. When button gets focus, this code will immediately give focus back to defaultFocusNode.

button.focusedProperty().addListener((observableValue, oldValue, newValue) -> {
        if (newValue)  defaultFocusNode.requestFocus();
      });
silvalli
  • 295
  • 2
  • 13