How to create a Menu using JavaFX?


A menu is a list of options or commands presented to the user. In JavaFX a menu is represented by the javafx.scene.control.Menu class, you can create a menu by instantiating this class.

While instantiating, you can pass the title of the menu as a parameter to its constructor. The Menu class contains an observable list that holds the contents of the menu (menu items).

Menu items and menu bar

The menu items are represented by the javafx.scene.control.MenuItem class, a superclass of the Menu class. You can display a text or a graphic as a menu item and add the desired cation to it.

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.

The javafx.scene.control.MenuBar class represents a menu bar that holds all the menus in a UI application.

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.paint.Color;
import javafx.stage.Stage;
public class MenuExample 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);
      //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: 18-May-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements