【问题标题】:Add a top menu to JavaFX centered Grid Pane将顶部菜单添加到以 JavaFX 为中心的网格窗格
【发布时间】:2019-03-27 04:56:25
【问题描述】:

我对 JavaFX 很陌生。无论窗口大小如何调整,我都使用网格窗格将我的项目保持在页面中心。我想添加一个在顶部运行的菜单。我很快发现 grid.setTop(menuBar) 不是网格窗格的成员函数。有办法吗?

我可以在一个场景中创建两种不同类型的窗格吗? IE,一个让项目居中的 GridPane 和一个让菜单位于顶部的 BorderPane?还是应该使用 CSS 样式将菜单栏置于顶部?

这是我正在使用的一些代码:

public void start(Stage primaryStage) {
    try {
    primaryStage.setTitle("Bapu Inventory");
    BorderPane root = new BorderPane();
    GridPane grid = new GridPane();
    grid.setAlignment(Pos.CENTER);
    grid.setHgap(10);
    grid.setVgap(10);
    grid.setPadding(new Insets(25, 25, 25, 25));
    Text scenetitle = new Text("Welcome");
    grid.add(scenetitle, 0, 0, 1, 1);


    MenuBar menuBar = new MenuBar();
    menuBar.prefWidthProperty().bind(primaryStage.widthProperty());
//This is the line I can't figure out. How do I get this to position at top left?
    grid.setTop(menuBar);

任何帮助将不胜感激。我查看了 Oracle 提供的文档,但没有在任何地方找到此功能。

【问题讨论】:

  • 我的建议:使用BorderPane,将您的菜单添加到其top。然后将您的 GridPane 添加到 BorderPane 的中心。
  • 创建 BorderPane 后我有什么特别需要做的吗?当我尝试这样做时,似乎 GridPane 会覆盖我在 BorderPane 中拥有的所有内容。
  • 如果您只向GridPane 添加单个元素,最好使用更简单的布局。 VBox 允许您将两者都添加为子项,并且可以设置为水平对齐TextVBox.margin 可用于替换填充...

标签: java css javafx gridpane


【解决方案1】:

检查这是不是你想要的:

public void start(Stage primaryStage) {
        try {
            BorderPane root = new BorderPane();

            //Create your menu
            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);

            //Your GridPane
            GridPane grid = new GridPane();
            grid.setAlignment(Pos.CENTER);
            grid.setHgap(10);
            grid.setVgap(10);
            grid.setPadding(new Insets(25, 25, 25, 25));
            Text scenetitle = new Text("Welcome");
            grid.add(scenetitle, 0, 0, 1, 1);

            //Add them  to root (BorderPane)
            root.setTop(menuBar);
            root.setCenter(grid);


            Scene scene = new Scene(root,400,400);
            primaryStage.setScene(scene);
            primaryStage.show();
        } catch(Exception e) {
            e.printStackTrace();
        }
}

【讨论】:

  • 这正是我想要的!我正在向后初始化它们。
猜你喜欢
  • 2014-10-12
  • 1970-01-01
  • 1970-01-01
  • 2021-03-27
  • 1970-01-01
  • 1970-01-01
  • 2014-01-20
  • 2018-11-15
  • 2011-12-22
相关资源
最近更新 更多