JavaFX MenuItem add to menu bar

Introduction

To add menu item to menu bar in JavaFX application

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

// Create the File menu.
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");
fileMenu.getItems().addAll(open, close, save, new SeparatorMenuItem(), exit);

// Add File menu to the menu bar.
mb.getMenus().add(fileMenu);//from   ww w .  j a v a2  s  . c  o  m

Full source

import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Scene;
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);/*w  w w. ja v a 2s . c o  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.
    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");
    fileMenu.getItems().addAll(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