package javaapplication5; import javafx.application.Application; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Menu; import javafx.scene.control.MenuBar; import javafx.scene.control.MenuItem; import javafx.stage.Stage; public class JavaApplication5 extends Application { public static void main(String[] args) { launch(args); } int count = 0; Menu fileMenu; @Override public void start(Stage stage) throws Exception { float h = 300; float w = 300; Scene scene; MenuBar menuBar = new MenuBar(); fileMenu = new Menu("File"); MenuItem menuitem = new MenuItem(); menuitem.setText("New"); fileMenu.getItems().clear(); fileMenu.getItems().addAll(menuitem); menuBar.getMenus().clear(); menuBar.getMenus().addAll(fileMenu); Button insertMenuItemButton = new Button("Insert MenuItem"); insertMenuItemButton.setTranslateX(50.0F); insertMenuItemButton.setTranslateY(50.0F); insertMenuItemButton.setOnAction(new EventHandler() { public void handle(ActionEvent e) { final MenuItem newMenuItem = new MenuItem(); newMenuItem.setText("Delete this menuItem " + count++); newMenuItem.setOnAction(new EventHandler() { @Override public void handle(ActionEvent t) { int i = fileMenu.getItems().indexOf(newMenuItem); if (i != -1) { fileMenu.getItems().remove(i); } } }); fileMenu.getItems().add(newMenuItem); } }); scene = new Scene(new Group(), w, h); ((Group) scene.getRoot()).getChildren().clear(); ((Group) scene.getRoot()).getChildren().addAll(menuBar, insertMenuItemButton); stage.setScene(scene); stage.show(); } }