编程语言
首页 > 编程语言> > 在FXML文件(JavaFX)中多次插入同一对象

在FXML文件(JavaFX)中多次插入同一对象

作者:互联网

我有一个带有2个标签的FXML文件.在每个选项卡中,我都有相同的Text元素列表.如何避免必须重复每个Text元素?

这是我的FXML文件的摘录:

<Tab>
    <GridPane>
        <columnConstraints>
            <ColumnConstraints />
        </columnConstraints>
        <rowConstraints>
            <RowConstraints />
            <RowConstraints />
            <RowConstraints />
            <RowConstraints />
        <RowConstraints />
        </rowConstraints>
        <children>
            <Text fx:id="text1" GridPane.rowIndex="1" />
            <Text fx:id="text2" GridPane.rowIndex="2" />
            <Text fx:id="text3" GridPane.rowIndex="3" />
            <Text fx:id="text4" GridPane.rowIndex="4" />
        </children>
    </GridPane>
</Tab>
<Tab>
    <GridPane>
        <columnConstraints>
            <ColumnConstraints />
        </columnConstraints>
        <rowConstraints>
            <RowConstraints />
            <RowConstraints />
            <RowConstraints />
            <RowConstraints />
        <RowConstraints />
        </rowConstraints>
        <children>
            <Text fx:id="text1" GridPane.rowIndex="1" />
            <Text fx:id="text2" GridPane.rowIndex="2" />
            <Text fx:id="text3" GridPane.rowIndex="3" />
            <Text fx:id="text4" GridPane.rowIndex="4" />
        </children>
    </GridPane>
</Tab>

如果将相同的id放在两个Text元素中(例如,两个选项卡中的fx:id =“ text1”),则会出现错误(重复的id引用).

解决方法:

可以使用fx:include和嵌套控制器重写fxml.

创建一个新的fxml文件sub.fxml,其中包含您重复的场景部分,例如

<Tab xmlns:fx="http://javafx.com/fxml/1" fx:controller="mypackage.SubController">
    <GridPane>
        <columnConstraints>
            <ColumnConstraints />
        </columnConstraints>
        <rowConstraints>
            <RowConstraints />
            <RowConstraints />
            <RowConstraints />
            <RowConstraints />
        <RowConstraints />
        </rowConstraints>
        <children>
            <Text fx:id="text1" GridPane.rowIndex="1" />
            <Text fx:id="text2" GridPane.rowIndex="2" />
            <Text fx:id="text3" GridPane.rowIndex="3" />
            <Text fx:id="text4" GridPane.rowIndex="4" />
        </children>
    </GridPane>
</Tab>

创建SubController类,并使相关部分可访问:

public class SubController {
    @FXML
    private Text text1;
    ...
    @FXML
    private Text text4;

    public void setText1(String text) {
        this.text1.setText(text);
    }

    ...
}

现在,更改“主要” fxml以使用随附的fxml:

<fx:include source="sub.fxml" fx:id="tab1" />
<fx:include source="sub.fxml" fx:id="tab2" />

并在父控制器中创建用于注入SubController的字段:

@FXML
private SubController tab1Controller;
@FXML
private SubController tab2Controller;

您将能够以与访问其他注入元素相同的方式访问控制器.例如.在第一个选项卡中设置text1的文本:

tab1Controller.setText1("Hello World!");

标签:javafx,fxml,java
来源: https://codeday.me/bug/20191026/1940000.html