Search code examples
javajavafxfxmlborderpane

JavaFX building borderPane with FXML files


Using a BorderPane layout, can you populate each part of it (top, left, center, right and bottom) using separate FXML files?

So I would have a main.fxml like:

<BorderPane fx:controller="main.mainController"  xmlns:fx="http://javafx.com/fxml" >

    <top>
        reads from top.fxml
    </top>

    <left>
        reads from left.fxml
    </left>

    <center>
        reads from center.fxml
    </center>

    <right>
        reads from right.fxml
    </right>

    <bottom>
        reads from bottom.fxml
    </bottom>

</BorderPane>


Solution

  • There are 2 ways to do it:

    add it in java

    After you load the BorderPane, you can load other FXML files and put them into the BorderPane.

    E.g.

    BorderPane root=FXMLLoader.load(this.getClass().getResource("root.fxml");//maybe this.getClass().getClassLoader().getResource("root.fxml"), depending on project structure
    AnchorPane center=FXMLLoader.load(this.getClass().getResource("center.fxml");//maybe this.getClass().getClassLoader().getResource("center.fxml"), depending on project structure
    root.setCenter(center);
    stage.setScene(new Scene(root));
    

    inside FXML

    As @Sedrick points out in the comments, you can also use fx:include:

    <center>
        <fx:include source="center.fxml"/>
    </center>
    

    In both options, it works the same with top, bottom, left and right.