I'm a newbie to JavaFx. In my JavaFX application I have set onAction property and it works fine when I press the button using mouse. I want to fire the same even when user press Enter on button. I know I can use a even handler to do that. But when I read the onAction JavaDoc it says that this event get fire by a key press.
Property description:
The button's action, which is invoked whenever the button is fired. This may be due to the user clicking on the button with the mouse, or by a touch event, or by a key press, or if the developer programmatically invokes the fire() method.
But when I press Enter key nothing happens. Is it error in documentation? Are there any other way to achieve that without adding alistener to the button?
P.S
After the comments I checked with space key then it get fired. But I want to set that to Enter key.
I have many buttons. I tried button.setDefaultButton(true);
but it is not get fired. I think that is becacuse there are more than one button. If I set it just to a single button it works fine. How to set that to multiple buttons?
You can create a Button by instantiating the javafx. scene. control. Button class of this package and, you can set text to the button using the setText() method.
To make a button do something in JavaFX you need to define the executable code usually by using a convenience method like setOnAction() . Then, when the button is clicked, JavaFX does the heavy lifting of fetching that pre-defined code, and executing it on the JavaFX Application thread.
You can dynamically change the default button property of the currently focused button by using binding
btn.defaultButtonProperty().bind(btn.focusedProperty());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With