import javafx.application.Application; import javafx.scene.layout.VBox; import javafx.scene.Scene; import javafx.stage.Stage; import javafx.scene.control.Menu; import javafx.scene.control.MenuBar; import javafx.scene.control.MenuItem; import javafx.scene.input.KeyCombination; public class MenuBarApp extends Application { public final static int MENUS_NUM = 3; public final static String MENU_STR = "Menu"; public final static int MENUS_DEPTH = 2; static MenuBar menuBar; private MenuBarApp.ShortcutGenerator shortcutGenerator = new MenuBarApp.ShortcutGenerator(); private void init(Stage primaryStage) { VBox root = new VBox(); root.setSpacing(200); Scene scene = new Scene(root, 350, 300); primaryStage.setScene(scene); primaryStage.setTitle("MenuBar Test (" + System.getProperty("javafx.runtime.version") + ")"); menuBar = new MenuBar(); root.getChildren().addAll(menuBar); reset(); } @Override public void start(Stage primaryStage) throws Exception { init(primaryStage); primaryStage.show(); } public static void main(String[] args) { launch(args); } private void reset() { menuBar.getMenus().clear(); for (int i = 0; i < MENUS_NUM; i++) { menuBar.getMenus().add(new MenuBarApp.BarItem(MENU_STR + i, MENUS_DEPTH)); } } private class ShortcutGenerator { private char c; private int mask; private String mods[] = new String[]{"ctrl", "alt", "shift"}; public ShortcutGenerator() { c = 'A'; mask = 0; } public ShortcutGenerator(char c, int mask) { this.c = c; this.mask = mask; } public KeyCombination getShortcut() { StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < mods.length; i++) { if (((mask >> i) & 1) != 0) { stringBuilder.append(mods[i]).append("+"); } } stringBuilder.append(c); if (++c > 'Z') { c = 'A'; mask++; } KeyCombination kk = KeyCombination.keyCombination(stringBuilder.toString()); return kk; } @Override public MenuBarApp.ShortcutGenerator clone() { return new MenuBarApp.ShortcutGenerator(c, mask); } } private class BarItem extends Menu { public BarItem(String str, int depth) { super(str); setStyle("-fx-font-size: 10px;"); addSubMenu(this, depth - 1); } private void addSubMenu(MenuItem root, int level) { for (int i = 0; i < MENUS_NUM; i++) { final MenuItem item; if (level > 0) { item = new Menu(root.getText() + " SubMenu " + i); } else { item = new MenuItem(root.getText() + " SubMenu Item " + i); } ((Menu) root).getItems().add(item); if (level > 0) { addSubMenu(item, level - 1); } else { item.setAccelerator(shortcutGenerator.getShortcut()); } } } } }