簡體   English   中英

JavaFx將其他FXML加載到FXML“模板”中

[英]JavaFx Loading additional FXML into FXML 'template'

我需要創建許多不同的FXML文件,並且每個文件都具有一致的布局。 每個都將具有一個AnchorPane,它將保存單獨的內容。

有沒有辦法加載“基本” FXML文件,然后加載第二個FXML文件,並將該數據路由到第一個文件中?

例如,FXML#1具有BorderPane。 FXML#2具有按鈕,texfield,標簽等。如何加載#1,然后作為#1的子代加載#2?

您可以使用<fx:root>元素允許您向現有元素添加一些內容。

你需要一種方式來獲得該應作為根元素節點的引用,並把它傳遞給FXMLLoader加載第二FXML時。 您可以例如使用名稱空間通過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"/>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM