This tutorial is part of JavaFX and shows you how to use the JavaFX ContextMenu that displays menu items when you right-click on a node. JavaFX ContextMenu is very easy to use. It is a pop-up control that will display a list of JavaFX MenuItems. This control is also known as a pop-up menu or context. By default, this control is hidden, and it will show by right-clicking a node like for example a button.
In this tutorial, you will know how to use the ContextMenu in JavaFX. I will walk you through the process of creating this control in JavaFX and adding some items to it using the menu items in JavaFX. This tutorial is easy to learn, especially for beginners. Please continue reading this tutorial to learn more about JavaFX ContextMenu.
How to use the JavaFX ContextMenu
To create a ContextMenu, we need to use the default constructor of the ContextMenu class to create an empty pop-up menu. Creating an object of ContextMenu is very easy, and it is the same as creating an object of other classes. The following example of code below will show you how to create an object of ContextMenu in JavaFX.
// Create a JavaFX ContextMenu ContextMenu contextMenu = new ContextMenu();
Now, we created an empty ContextMenu and the next step we need to do is to add items to the JavaFX ContextMenu. These items are the JavaFX MenuItems, I assume you already know how to create a menu item in JavaFX.
Add items to the ContextMenu
Adding items to the JavaFX ContextMenu is very easy. In this example, let’s assume that we already created our Menu items for our ContextMenu. We need to use the getItems() and addAll() methods since we need to add multiple menu items. The following example code will show you how to add items to the ContextMenu in JavaFX.
// Create a JavaFX ContextMenu ContextMenu contextMenu = new ContextMenu(); contextMenu.getItems().addAll(item1, item2, item3);
You can also add initial items to the ContextMenu by using its other constructor. By doing that, please see the example code below to learn more.
// Create a JavaFX ContextMenu ContextMenu contextMenu = new ContextMenu(item1, item2, item3);
By adding an item to the ContextMenu, make sure you have already created the JavaFX MenuItems.
Display the ContextMenu
Showing the ContextMenu in our application is very easy. You just need to right-click, and it will pop up, but you need to attach this control to any node. For example, you can use JavaFX Button or JavaFX TextField. You need to use the node’s setContextMenu() method to attach the JavaFX ContextMenu, and it will show when you right-click the node. The following example code below will show you how to do it.
Button btn = new Button("Right Click"); btn.setContextMenu(contextMenu);