HBox:适合父级AnchorPane Javafx,不使用FXML

时间:2016-04-18 19:09:33

标签: javafx hbox

我们如何像在FXML sceneBuilder中那样设置hbox适合其父AnchorPane。

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();

I want menuBar to get auto resize when window is resized.

1 个答案:

答案 0 :(得分:1)

您必须为hbox设置AnchorPane约束:

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

(但使用MenuBar的首选方式是将其置于BorderPane的顶部