0

我们如何像在 FXML 场景构建器中那样设置一个适合其父 AnchorPane 的 hbox。

AnchorPane root = new AnchorPane();
        Scene scene = new Scene(root, 700, 500);
        scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());

        //MenuBar
        MenuBar menuBar=new MenuBar();
        Menu file=new Menu("File");
        MenuItem loadStudentData=new MenuItem("Load Student Data  Ctrl+L");
        MenuItem saveStudentData=new MenuItem("Save Student Data  Ctrl+S");
        MenuItem exit=new MenuItem("Exit       Ctrl+X");
        Menu help=new Menu("Help");
        MenuItem about=new MenuItem("About");

        file.getItems().add(loadStudentData);
        file.getItems().add(saveStudentData);
        file.getItems().add(exit);
        help.getItems().add(about);

        menuBar.getMenus().addAll(file);
        menuBar.getMenus().addAll(help);

        HBox hboxMenu=new HBox();
        hboxMenu.getChildren().add(menuBar);

        HBox.setHgrow(menuBar, Priority.ALWAYS);

        root.getChildren().add(hboxMenu);

        primaryStage.setScene(scene);
        primaryStage.show();

我希望 menuBar 在调整窗口大小时自动调整大小。

4

1 回答 1

1

您必须为 hbox 设置 AnchorPane 约束:

    AnchorPane.setLeftAnchor(hboxMenu, 0d);
    AnchorPane.setRightAnchor(hboxMenu, 0d);

(但使用 a 的首选方法MenuBar是将其放在 a 的顶部BorderPane

于 2016-04-18T19:19:56.307 回答