How to disable a menu item in JavaFX

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.

Disabling a MenuItem

The MenuItem class contains a property named visible (boolean), which specifies whether to display the current MenuItem. You can set the value to this property using the setVisible() method.

To disable a particular menu item invoke the setVisible() method on its object by passing the boolean value “false”.


import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class DisablingMenuItems extends Application {
   public void start(Stage stage) {
      //Creating a menu
      Menu fileMenu = new Menu("File");
      //Creating menu Items
      MenuItem item1 = new MenuItem("Add Files");
      MenuItem item2 = new MenuItem("Start Converting");
      MenuItem item3 = new MenuItem("Stop Converting");
      MenuItem item4 = new MenuItem("Remove File");
      MenuItem item5 = new MenuItem("Exit");
      //Adding all the menu items to the menu
      fileMenu.getItems().addAll(item1, item2, item3, item4, item5);
      //Disabling menu items
      //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);
      stage.setTitle("Menu Example");
   public static void main(String args[]){

Updated on: 20-May-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started