How to create CheckMenuItem 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.

JavaFx supports three kinds of menu items namely − check menu item, custom menu item, and, radio menu item.

CheckMenuItem

A CheckMenuItem is a special MenuItem that has a checkmark (tick) similar to the checkbox. This has two states selected (with a checkmark) and unselected (without checkmark). It is represented by the javafx.scene.control.CheckMenuItem class.

To add a CheckMenuItem in the menu −

  • Instantiate the Menu class.

  • Instantiate the CheckMenuItem class.

  • Add all the created check menu menu-item to the menu as −

menu.getItems().add(item);
  • Create a menu bar by instantiating the MenuBar class.

  • Add the menu to the menu bar as −

menuBar.getMenus().add(menu);
  • Add the menu bar to the scene.

Example

import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.CheckMenuItem;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.control.SeparatorMenuItem;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class CheckMenuItemExample extends Application {
   @Override
   public void start(Stage stage) {
      //Creating a menu
      Menu fileMenu = new Menu("File");
      //Creating menu Items
      Menu view = new Menu("View");
      MenuItem edit = new MenuItem("Edit");
      MenuItem exit = new MenuItem("Exit");
      //Creating menu items for the sub item edit
      CheckMenuItem sub1 = new CheckMenuItem("Status Bar");
      CheckMenuItem sub2 = new CheckMenuItem("Address Bar");
      CheckMenuItem sub3 = new CheckMenuItem("Tool Bar");
      //Adding sub items to the edit
      view.getItems().addAll(sub1, sub2, sub3);
      //Creating a separator
      SeparatorMenuItem sep = new SeparatorMenuItem();
      //Adding all the menu items to the menu
      fileMenu.getItems().addAll(edit, view, sep, exit);
      //Creating a menu bar and adding menu to it.
      MenuBar menuBar = new MenuBar(fileMenu);
      menuBar.setTranslateX(200);
      menuBar.setTranslateY(20);
      //Setting the stage
      Group root = new Group(menuBar);
      Scene scene = new Scene(root, 595, 200, Color.BEIGE);
      stage.setTitle("Menu Example");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}

Output

Updated on: 20-May-2020

456 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements