JAVA FX: 如何在FXML视图的同一场景中设置菜单栏

huangapple go评论73阅读模式
英文:

JAVA FX : How to set menubar in same scene of fxml view

问题

我想将我的菜单栏从边界面板添加出来,但问题实际上是我在主舞台上加载了我的视图(FXML)。我想在视图顶部添加我的菜单栏:

Parent root = FXMLLoader.load(getClass().getResource("/view/home/home.fxml"));

// 创建菜单栏
MenuBar menuBar = new MenuBar();

// 创建菜单
Menu fileMenu = new Menu("文件");
Menu editMenu = new Menu("编辑");
Menu helpMenu = new Menu("帮助");

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

primaryStage.setScene(new Scene(root, 900, 600));
primaryStage.setScene(new Scene(rootTop, 900, 600));

primaryStage.show();
英文:

I wouldlke to add my menubar from my borderpane but the problem actually is I loaded my view (FXML) on primary stage. I wouldike to add my menubar at top of my view :

Parent root = FXMLLoader.load(getClass().getResource("/view/home/home.fxml"));

// Create MenuBar
MenuBar menuBar = new MenuBar();

// Create menus
Menu fileMenu = new Menu("File");
Menu editMenu = new Menu("Edit");
Menu helpMenu = new Menu("Help");

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

primaryStage.setScene(new Scene(root, 900, 600));
primaryStage.setScene(new Scene(rootTop, 900, 600));

primaryStage.show();

答案1

得分: 0

以下是翻译好的部分:

这段代码:

primaryStage.setScene(new Scene(root, 900, 600));
primaryStage.setScene(new Scene(rootTop, 900, 600));

设置了场景两次。第二个 Scene 覆盖了第一个,所以您将无法看到已加载的 FXML。

您可以做的是将您的 FXML 嵌入 到您的 BorderPane 中:

BorderPane rootTop = new BorderPane();
rootTop.setTop(menuBar);
rootTop.setCenter(root);

primaryStage.setScene(new Scene(rootTop, 900, 600));

primaryStage.show();
英文:

This code:

primaryStage.setScene(new Scene(root, 900, 600));
primaryStage.setScene(new Scene(rootTop, 900, 600));

sets the scene two times. The second Scene overrides the first one, so you won't be able to see your loaded FXML.

What you can do is embed your FXML in your BorderPane:

BorderPane rootTop = new BorderPane();
rootTop.setTop(menuBar);
rootTop.setCenter(root);

primaryStage.setScene(new Scene(rootTop, 900, 600));

primaryStage.show();

huangapple
  • 本文由 发表于 2020年9月7日 18:13:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/63775558.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定