Shoaib Khan
Shoaib Khan

Reputation: 51

HBox: fit to parent AnchorPane Javafx, not using FXML

How can we set an hbox fit to its parent AnchorPane as we do in FXML sceneBuilder.

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.

Upvotes: 0

Views: 1386

Answers (1)

jns
jns

Reputation: 6952

You have to set the AnchorPane constraints for hbox:

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

(But the prefered way to use a MenuBar is putting it into the top of a BorderPane)

Upvotes: 1

Related Questions