JavaFX CheckMenuItem create and add to menu

Introduction

To create CheckMenuItem and add to menu in JavaFX

CheckMenuItem red = new CheckMenuItem("Red");

Full source

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.CheckMenuItem;
import javafx.scene.control.Label;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.control.SeparatorMenuItem;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;

public class Main extends Application {
  //Create a label that will report the selection.
  private Label response = new Label("Menu Demo");

  public static void main(String[] args) {
    launch(args);/*from  w  w w.  j a va 2 s . co m*/
  }
  public void start(Stage myStage) {    myStage.setTitle("Menus from java2s.com");

    // Use a BorderPane for the root node.
    BorderPane rootNode = new BorderPane();

    Scene myScene = new Scene(rootNode, 300, 300);

    myStage.setScene(myScene);

    // Create the menu bar.
    MenuBar mb = new MenuBar();

    // Create the File menu, including a mnemonic.
    Menu fileMenu = new Menu("_File");
    MenuItem open = new MenuItem("Open");
    MenuItem close = new MenuItem("Close");
    MenuItem save = new MenuItem("Save");
    MenuItem exit = new MenuItem("Exit");
    
    // Create the Colors submenu.
    Menu colorsMenu = new Menu("Colors");

    // Use check boxes for colors. This allows
    // the user to select more than one color.
    CheckMenuItem red = new CheckMenuItem("Red");
    CheckMenuItem green = new CheckMenuItem("Green");
    CheckMenuItem blue = new CheckMenuItem("Blue");

    // Select green for the default color selection.
    green.setSelected(true);

    // Add the check menu items for the colors menu and
    // add the colors menu to the options menu.
    colorsMenu.getItems().addAll(red, green, blue);

    
    fileMenu.getItems().addAll(colorsMenu,open, close, save, new SeparatorMenuItem(), exit);

    // Add File menu to the menu bar.
    mb.getMenus().add(fileMenu);

    // the response label to the center position.
    rootNode.setTop(mb);
    rootNode.setCenter(response);

    myStage.show();
  }
}



PreviousNext

Related