JavaFX Menu and MenuBar


JavaFX Menu and MenuBar Tutorials:

JavaFX Menu and Menu Bar are set of options presented to execute a capable functions.

What is difference between Menu, Menu Bar and Menu Item ?

MenuBar : Horizontal bar containing Menus.

Menu : It containing MenuItems in vertically.

MenuItem : A function which can be performed by application.

Constructors of Menu :

  • Menu()Constructs a Menu with an empty string for its display text.
  • Menu(String text)Constructs a Menu and sets the display text with the specified text.
  • Menu(String text, Node graphic)Constructs a Menu and sets the display text with the specified text and sets the graphic Node to the given node.
  • Menu(String text, Node graphic, MenuItem… items)Constructs a Menu and sets the display text with the specified text, the graphic Node to the given node, and inserts the given items into the items list.

Constructors of Menu bar:

  • MenuBar()Creates a new empty MenuBar.
  • MenuBar(Menu… menus)Creates a new MenuBar populated with the given menus.

Creating MenuBar :

To create menu

Menu menu = new Menu("File");

Creating MenuBar AS

MenuBar menuBar = new MenuBar();

getItems() method is used to show MenuItems within the menu.


getMenus() used to show(get) menus within the menuBar

menuBar.getMenus().addAll(menu, menu1, menu2);

Example of menu and menubar:

package javafxtuts;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;

public class Javafxtuts extends Application {

  public static void main(String[] args) {

  public void start(Stage stage) {
      //crete menuBar
      MenuBar menuBar = new MenuBar();
      //crete menus
       Menu menu = new Menu("File");
       Menu menu1 = new Menu("Edit");
       Menu menu2 = new Menu("Help");
       //crete menuItems
        MenuItem menuItem=new MenuItem("New Project");
        MenuItem menuItem1=new MenuItem("New File");
        MenuItem menuItem2=new MenuItem("Open Project");
        MenuItem menuItem3=new MenuItem("Undo");
        MenuItem menuItem4=new MenuItem("Redo");
        // add menuItems to the Menus
        //add menus to the menuBar
       menuBar.getMenus().addAll(menu, menu1, menu2);
      BorderPane root = new BorderPane();
        Scene scene = new Scene(root, 300, 200);


Explanation of menu & menu bar example:

  • creating menu Item ASMenuItem menuItem=new MenuItem("New Project");
  • menu.getItems().addAll(menuItem,menuItem1,menuItem2);It add these MenuItems to the menu.
  • menuBar.getMenus().addAll(menu, menu1, menu2);It add these Menus to the menubar.
  • BorderPane root = new BorderPane();root.setTop(menuBar);

    It create a BorderPane Layout and set top of BorderPane to menuBar.


Leave A Reply