How to Add a Keyboard Shortcut to a Menu in JavaFX 


               


How to Add a Keyboard Shortcut to a Menu in JavaFX

Java


In this article, we show how to add a keyboard shortcut to a menu in JavaFX.

This is so that instead of clicking a menu item to access it, it can be accessed by pressing the Alt key followed by the first letter in the menu item.

So if one of the menus in the menu bar is File, then to access it, a user can click Alt + F. This will drop down the File menu, displaying all of its menu items.

In JavaFX, we can add this functionality very easily to a menu.

In order to do so, all you have to do is add an underscore(_) before the name of the menu.

This is shown in the code below.



Simply by adding that underscore (_) before File means we have created a way for a user this File menu through a keyboard shortcut (Alt + F).

This way, a user does not have to have a mouse and drag it to the File menu and click it. It can also be accessed by keyboard shortcut.

In our full Java code example shown below, we make both the File menu and the Edit menu both keyboard shortcut accessible. So that to access the File menu, the user presses Alt + F. To access the Edit menu, the user pressed Alt + E.





So we import all the packages we need, create our class, override the start method, and set the title of our stage.

We then create our menu bar, which will hold all the menus we create. In this code, we create a File menu and an Edit Menu.

We then create the File menu. When creating the File menu, when passing the name of the menu, we place an underscore (_) before the File menu. This gives the keyboard shortcut to the File menu when the user presses Alt + F.

We do the same for the Edit menu. When creating this menu, we pass in an underscore before Edit. This menu can now be accessed by pressing Alt + E.

You will notice that when you have the window opened and you press down Alt, the Menus will have the first letter underlined. This signals to the user that if the user presses down this letter, it will open up the menu, showing its menu items.

And this is all that is necessary to give keyboard shortcuts to menus in JavaFX.


Related Resources

How to Retrieve Data from a Text Field in JavaFX

How to Retrieve Data from a Radio Button Group in JavaFX

How to Retrieve Data from a Group of Check Boxes in JavaFX

How to Retrieve Data from a ChoiceBox in JavaFX

How to Retrieve Data from a ListView

How to Check if a Text Field is Empty in JavaFX

How to Select an Item By Default in JavaFX

How to Disable a Button After It's Clicked in JavaFX




HTML Comment Box is loading comments...