How to Add Functionality to a Menu in JavaFX

Java


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

Before, we showed how to create a menu in JavaFX. Now we extend that tutorial and show how to add functionality to the menu so that when a menu item is clicked, something is done.

So it's actually pretty simple to add functionality to a menu item.

It's the simple use of event handlers. You attach an event handler to a menu item. And then in the event handling code, you can specify what you want done.

In this code, we're going to add functionality to the exit menu item in the File menu. When you click the exit menu item, the window closes.

So below is the full Java code to implement this.





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.

We then create all the items in the File menu.

To do this, we first create the menu item. The first menu item that we create is the "New Project..." menu item. So we create this through the line, MenuItem newproject= new MenuItem("New Project...");

We then add this menu item to the file menu through the line, filemenu.getItems().add(newproject);

And we repeat this for all the other menu items.

Now, in this code, we add functionality to the exit menu item in the File menu.

How we do this is through event handling.

We use event handling so that the window closes upon the exit menu item being clicked. We do this through the line, exit.setOnAction(e -> Platform.exit());

This line will close the window when the exit menu item is clicked.

And this is all that is required to add functionality to menu in JavaFX.

Simply by using event handling, you can do any action when an item is clicked.

Again, for this program, only the exit menu item has functionality but you can easily apply this to any menu item not that you know it's just event handling using lambda expressions to do the job.


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...