How to create sub menus 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. You can create a menu by instantiating the javafx.scene.control.Menu class.

Adding sub menus

To create a menu −

  • Instantiate the Menu class.

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

  • Add the created menu items to the observable list of the menu.

To add sub-menu, you just need to add a menu to another menu.

Example

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.control.SeparatorMenuItem;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class SubMenuExample extends Application {
   @Override
   public void start(Stage stage) {
      //Creating a menu
      Menu fileMenu = new Menu("File");
      //Creating menu Items
      MenuItem save = new MenuItem("Save");
      Menu edit = new Menu("Edit");
      MenuItem remove = new MenuItem("Remove");
      MenuItem exit = new MenuItem("Exit");
      //Creating menu items for the sub item edit
      MenuItem sub1 = new MenuItem("Copy");
      MenuItem sub2 = new MenuItem("Paste");
      //Adding sub items to the edit
      edit.getItems().addAll(sub1, sub2);
      //Creating a separator
      SeparatorMenuItem sep = new SeparatorMenuItem();
      //Adding all the menu items to the menu
      fileMenu.getItems().addAll(save, edit, remove, 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

raja
Published on 20-May-2020 10:53:57
Advertisements