我正在尝试学习 JavaFX,但我的 MenuBar
中的 Menus
遇到了问题。这是一个最小的例子:
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();
}
此应用程序启动,但 MenuBar
中的 Menu
仅显示为三个点 (...)。但是,当我按 ALT+F
时,它确实会打开,所以它就在那里。
据我了解,Menu
项没有 width
或类似属性,因此无法设置。我怀疑这与我的根节点是 BorderPane
有关,因为在我发现有效的每个其他示例中,根节点要么是 VBox
要么是其他东西。当我将 Vbox
作为根节点,然后将 MenuBar
和 BorderPane` 添加到根节点时,我似乎得到了所需的结果 - 但这似乎很奇怪对我来说是不必要的解决方法。
那么我在这里错过了什么? MenuBar
真的只会在某些容器中看起来像它应该的那样吗?在这方面,BorderPane
和 VBox
之间有什么区别?如果有人可以解释或指出我错过的部分文档,我将非常感激。
最佳答案
您正在使用 BorderPane
并使用 getChildren().add()
在其中添加 MenuBar,这是不正确的。 BorderPane
与 VBox
不同,不能接受任意数量的子元素,并且分为 5 个特定位置:
- 顶部
- 左
- 右
- 底部
- 居中
children 可以担任这些职位中的任何一个。 Please go through the documentation for BorderPane .
您需要使用以下方法将菜单栏添加到 BorderPane 的顶部:
root.setTop(menuBar);
关于JavaFX:在 BorderPane 中时菜单项仅显示为三个点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28579154/