JavaFX: Creating Menu Items

This entry is part 41 of 55 in the series JavaFX

In this example, we will continue to add 2 menu items to the File menu.

To create menu items, we use the MenuItem class.

Here we create 2 menu items, Open and Exit and we use addAll() to add to the File menu.

We will also add 2 corresponding event actions when we have clicked on the menu items.

package javafxapplication30;

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.stage.Stage;

public class JavaFXApplication30 extends Application {

    public void start(Stage stage) {

        stage.setTitle("JavaFX Program");

        HBox pane = new HBox();

        Scene scene = new Scene(pane, 400, 350);

        MenuBar menuBar = new MenuBar();

        final Menu menu1 = new Menu("File");
        final Menu menu2 = new Menu("Options");
        final Menu menu3 = new Menu("Help");

        MenuItem menuOpen = new MenuItem("Open");
        MenuItem menuClose = new MenuItem("Exit");
        menu1.getItems().addAll(menuOpen, menuClose);

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

        menuOpen.setOnAction(new EventHandler<ActionEvent>() {
            public void handle(ActionEvent e) {
                System.out.println("Opening Database Connection...");
        menuClose.setOnAction(new EventHandler<ActionEvent>() {
            public void handle(ActionEvent e) {

        HBox.setHgrow(menuBar, Priority.ALWAYS);  //So that the menuBar will take the whole HBox

    public static void main(String[] args) {



Series Navigation<< JavaFX: Setting up menu in a window
JavaFX: The default theme >>