Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fire Button's onAction with Enter in JavaFX

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?

like image 746
Thusitha Thilina Dayaratne Avatar asked Sep 10 '14 06:09

Thusitha Thilina Dayaratne


People also ask

How do you add a button to a scene in JavaFX?

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.

Do something when button is pressed JavaFX?

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.


1 Answers

You can dynamically change the default button property of the currently focused button by using binding

btn.defaultButtonProperty().bind(btn.focusedProperty());
like image 88
Uluk Biy Avatar answered Oct 07 '22 08:10

Uluk Biy