How to make an OS X menubar in JavaFX

2019-01-31 13:12发布

问题:

I'm unable to make a JavaFX MenuBar show as a standard OS X menu bar, at the top of the screen.

Here's what I've tried in my subclass of Application:

public void start(Stage primaryStage) throws Exception {
    final Menu menu1 = new Menu("File");
    final Menu menu2 = new Menu("Options");
    final Menu menu3 = new Menu("Help");

    MenuBar menuBar = new MenuBar();
    menuBar.getMenus().addAll(menu1, menu2, menu3);
    menuBar.setUseSystemMenuBar(true);

    primaryStage.setTitle("Creating Menus with JavaFX 2.0");
    final Group rootGroup = new Group();
    final Scene scene = new Scene(rootGroup, 800, 400, Color.WHEAT);


    rootGroup.getChildren().add(menuBar);
    primaryStage.setScene(scene);
    primaryStage.show();
}

I assumed that the use of

menuBar.setUseSystemMenuBar(true);

would do the trick, but actually it makes the menuBar disappear altogether.

I'm using Java 1.8.0-b132 on OS X 10.9

回答1:

I've had success with this code:

MenuBar menuBar = new MenuBar();
final String os = System.getProperty("os.name");
if (os != null && os.startsWith("Mac"))
  menuBar.useSystemMenuBarProperty().set(true);

BorderPane borderPane = new BorderPane();
borderPane.setTop(menuBar);

primaryStage.setScene(new Scene(borderPane));


回答2:

It looks like OS X only displays the Menus if they have MenuItems inside them (which is a bit weird, as you can attach functionality to empty Menus).



回答3:

I created a little project that gives you access to the auto-generated menu bar on OS X: NSMenuFX

Update: With the new pure JavaFX version, the API has slightly changed

It allows you to replace the default Mac OS menu bar items, so you can to something like this:

// Get the toolkit
MenuToolkit tk = MenuToolkit.toolkit();

// Create default application menu with app name "test"
Menu defaultApplicationMenu = tk.createDefaultApplicationMenu("test");

// Replace the autogenerated application menu
tk.setApplicationMenu(defaultApplicationMenu);

// Since we now have a reference to the menu, we can rename items
defaultApplicationMenu.getItems().get(1).setText("Hide all the otters");

You can of course also add new menu items as you do in your example above.



回答4:

I just ran into this issue myself - I noticed that the system menubar wouldn't initially appear in OSX until I switched to another application and back.

Wrapping the setUseSystemMenuBar call in a runLater did the trick, so I unscientifically concluded there's more window setup required before OSX can successfully register an application menu.

Platform.runLater(() -> menuBar.setUseSystemMenuBar(true));


回答5:

Building on dmolony with some corrections:

MenuBar menuBar = new MenuBar ();
  if( System.getProperty("os.name","UNKNOWN").equals("Mac OS X")) {
  menuBar.setUseSystemMenuBar(true);
}

BorderPane borderPane = new BorderPane ();
borderPane.setTop (menuBar);
primaryStage.setScene (new Scene (borderPane));


标签: javafx-2