【问题标题】:JavaFx Loading additional FXML into FXML 'template'JavaFx 将额外的 FXML 加载到 FXML '模板'
【发布时间】:2017-02-04 23:33:38
【问题描述】:

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

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

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

【问题讨论】:

    标签: java javafx fxml


    【解决方案1】:

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

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

    【讨论】:

    • 小心以句点开头的源 - 不会将规范解释为支持它们:以斜杠字符开头的值被视为相对于类路径。没有前导斜杠的值被认为是相对于当前文档的路径。
    【解决方案2】:

    您可以使用&lt;fx:root&gt; 元素向现有元素添加内容。

    您需要一种方法来获取对应用作根元素的节点的引用,并在加载第二个 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>
    

    【讨论】:

    • 效果很好,谢谢! .setRoot() sn-p 就像魔术一样工作并解决了我所有的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-08
    • 1970-01-01
    • 2013-07-22
    • 2017-03-17
    • 1970-01-01
    • 2016-11-07
    相关资源
    最近更新 更多