How to create CustomMenuItem in JavaFX?

JavaFXObject Oriented ProgrammingProgramming

A menu is a list of options or commands presented to the user, typically menus contain items that perform some action. The contents of a menu are known as menu items and a menu bar holds multiple menus.

In JavaFX a menu is represented by the javafx.scene.control.Menu class, a menu item is represented by the javafx.scene.control.MenuItem class, And, the javafx.scene.control.MenuBar class represents a menu bar. To create a menu −

  • Instantiate the Menu class.

  • Create a required number of menu items by instantiating the MenuItem class.

  • Add all the menu items to the menu as −

fileMenu.getItems().addAll(item1, item2, item3);
  • Create a menu bar by instantiating the MenuBar class.

  • Add all the created menus to the menu bar as −

menuBar.getMenus().addAll(fileMenu, fileList, skin);
  • Add the menu bar to the scene.

Custom MenuItem

JavaFX provides a class named javafx.scene.control.CustomMenuItem (a subclass of the MenuItem) in which you can embed an arbitrary node i.e. using this class you can add the arbitrary nodes (such as sliders, hyperlinks, etc.) to a Menu.

This class provides a property named content specifying the node to display. You can set the value to this property using the setContent() method.

To add a node to the CustomMenuItem you need to pass its objects as a parameter to the setContent() method of the constructor of the CustomMenu class.

Note − If you add arbitrary nodes to a menu in this way, they appear more natural.


import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.CustomMenuItem;
import javafx.scene.control.Hyperlink;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.Slider;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class CustomMenuItemExample extends Application {
   public void start(Stage stage) {
      //Creating a slider
      Slider slider = new Slider(0, 100, 0);
      slider.setStyle("-fx-background-color: GRAY");
      //Creating a Hiperlink
      Hyperlink link = new Hyperlink("");
      link.setStyle("-fx-background-color: floralwhite");
      //Creating menu
      Menu fileMenu = new Menu("File");
      //Creating the custom menu Items
      CustomMenuItem menuItem1 = new CustomMenuItem(slider);
      CustomMenuItem menuItem2 = new CustomMenuItem(link);
      fileMenu.getItems().addAll(menuItem1, menuItem2);
      //Creating a menu bar and adding menu to it.
      MenuBar menuBar = new MenuBar(fileMenu);
      //Setting the stage
      Group root = new Group(menuBar);
      Scene scene = new Scene(root, 595, 200, Color.BEIGE);
   public static void main(String args[]){


Published on 20-May-2020 07:07:43