JavaFX: FXML: How to make the child to extend its size to fit the parent pane?

Dean Chiu picture Dean Chiu · Mar 8, 2014 · Viewed 74.6k times · Source

I have managed to load a child fxml(sub UI) under a parent fxml (mainMenu UI). I have created an AnchorPane with id "mainContent". This pane is bound to 4 sides and changes in accords to the stage.

The child window will be loaded into the "mainContent" anchorpane. However, I can't figure out how to make the child to change along with its parent "mainContent".

My child UI is called like this.

@FXML
private void mnuUserLevel_onClick(ActionEvent event) {
    FXMLLoader loader = new FXMLLoader(getClass().getResource("DBedit.fxml"));
    loader.setController(new DBeditEntityUserlevel());

    try {
           Node n = (Node)loader.load();
           mainContent.getChildren().add(n);
    } catch (IOException e){
           System.out.println(e.getMessage());
    }
}

To further illustrate my question, please see my snap shot. The red square is the child. The yellow square is the "mainContent" AnchorPane of the MainMenu parent.

enter image description here

Answer

Sascha B picture Sascha B · Mar 8, 2014

If you set the static methods setTopAnchor( child, value ), setBottomAnchor( ... ), setLeftAnchor( ... ), setRightAnchor( ... ) of class AnchorPane to 0.0, the child Node will get stretched to the full extend of the parent AnchorPane.

Documentation Link: AnchorPane

edit: in the documentation link you can also see how you can set these values in your java code.

FXML example:

<AnchorPane fx:id="mainContent" ...>
<StackPane fx:id="subPane" AnchorPane.topAnchor="0.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" ></StackPane>
</AnchorPane>