I am trying to learn JavaFX and I've run into a problem with the Menus
in my MenuBar
. Here is a minimal example:
public void start(Stage mainStage) throws Exception {
BorderPane root = new BorderPane();
Scene scene = new Scene(root, 1200, 1000, Color.WHITE);
MenuBar menuBar = new MenuBar();
Menu menuFile = new Menu("_File");
menuBar.getMenus().add(menuFile);
MenuItem add = new MenuItem("_New");
menuFile.getItems().add(add);
root.getChildren().add(menuBar);
menuBar.prefWidthProperty().bind(mainStage.widthProperty());
mainStage.setScene(scene);
mainStage.show();
}
This application starts, but the Menu
in the MenuBar
is only shown as three dots (...). It does open however when I press ALT+F
, so it is there.
From what I understand, a Menu
item has no width
or similar attribute, so that can't be set. I suspect it has something to do with my root node being a BorderPane
, because in every other example I found that works, the root is either a VBox
or something else. I seem to get the desired results when I place a Vbox
as my root node, and then add the MenuBar
and the BorderPane` to the root - but that seems like a strange and uneccesary workaround to me.
So what am I missing here? Is it true that a MenuBar
will only ever look like it should in certain containers? What is the difference between a BorderPane
and a VBox
in this regard? If someone could explain or point me to a part of the documentation that I've missed, I would be very thankful.
You are using a BorderPane
and using getChildren().add()
to add MenuBar in it, which is incorrect. BorderPane
unlike VBox
, can't accept any number of children and is divided into 5 specific positions :
The children goes into any one of these positions. Please go through the documentation for BorderPane.
You need to add the Menubar to the top of the BorderPane using :
root.setTop(menuBar);