JavaFx 将额外的 FXML 加载到 FXML 'template'

JavaFx Loading additional FXML into FXML 'template'

我需要创建许多不同的 FXML 文件,每个文件都有一致的布局。每个都有一个 AnchorPane 来保存单独的内容。

有没有办法加载一个 'base' FXML 文件,然后加载第二个 FXML 文件,并将该数据路由到第一个?

例如,FXML #1 有一个 BorderPane。 FXML #2 有一个按钮、texfield、标签等。如何加载 #1,然后将 #2 作为 #1 的子项加载?

您可以使用 <fx:root> 元素向现有元素添加内容。

您需要一种方法来获取对应用作根元素的节点的引用,并在加载第二个 fxml 时将其传递给 FXMLLoader。你可以例如使用名称空间通过 fx:id 属性获取该元素:

@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>

或者您实际上可以像这样包含模板文件

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