haz
haz

Reputation: 2288

JavaFx Loading additional FXML into FXML 'template'

I need to create many different FXML files, and each of these has a consistent layout. Each will have an AnchorPane which will hold seperate content.

Is there a way to load a 'base' FXML file, and then load a second FXML file, and route that data into the first?

For example, FXML #1 has a BorderPane. FXML #2 has a button, texfield, label etc. How do I load #1, and then load #2 as a child of #1?

Upvotes: 1

Views: 2507

Answers (2)

MAYOBYO HASSAN
MAYOBYO HASSAN

Reputation: 506

or you can actually include the template file like this

<fx:include source="../templates/my_template.fxml"/>

Upvotes: 0

fabian
fabian

Reputation: 82451

You could use the <fx:root> element to allow you to add something to a existing element.

You'll need a way to get a reference to the node that should be used as root element and pass it to the FXMLLoader when loading the second fxml. You could e.g. use the namespace to get that element using the fx:id attribute:

@Override
public void start(Stage primaryStage) throws IOException {
    FXMLLoader outerLoader = new FXMLLoader(getClass().getResource("outer.fxml"));

    Scene scene = new Scene(outerLoader.load());

    URL inner = getClass().getResource("inner1.fxml");
    // URL inner = getClass().getResource("inner2.fxml");

    FXMLLoader innerLoader = new FXMLLoader(inner);

    // get insertion point from outer fxml
    innerLoader.setRoot(outerLoader.getNamespace().get("insertionPoint"));

    innerLoader.load();

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

outer.fxml

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.layout.*?>

<AnchorPane prefHeight="400.0" prefWidth="600.0" xmlns:fx="http://javafx.com/fxml/1">
    <children>
        <BorderPane AnchorPane.topAnchor="10"  fx:id="insertionPoint"/>
    </children>
</AnchorPane>

inner1.fxml

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>

<fx:root type="javafx.scene.layout.BorderPane" xmlns:fx="http://javafx.com/fxml/1">
    <center>
        <Label text="Hello from inner 1."/>
    </center>
</fx:root>

inner2.fxml

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>

<fx:root type="javafx.scene.layout.BorderPane" xmlns:fx="http://javafx.com/fxml/1">
    <center>
        <Label text="Greetings from inner 2."/>
    </center>
</fx:root>

Upvotes: 3

Related Questions