提问者:小点点

JavaFX控制器注入不起作用


我有两个<code>fxml</code>文件。我用include语句将它们连接起来:

“主”fxml文件如下所示:

<?import javafx.geometry.*?>
// ...

<BorderPane prefHeight="962" prefWidth="1280" xmlns="http://javafx.com/javafx/8.0.40" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.MyMainController">
    <center>
        <SplitPane dividerPositions="0.63" BorderPane.alignment="CENTER">
            <items>
                <fx:include source="AnotherFile.fxml" />
                // ...
            </items>
        </SplitPane>
    </center>
    <top>
        // ...
    </top>
</BorderPane>

第二个(="antherFile. fxml")是这样的:

<?import java.lang.*?>
// ...

<SplitPane dividerPositions="0.15" orientation="VERTICAL" prefHeight="400.0" prefWidth="500.0" xmlns="http://javafx.com/javafx/8.0.40" xmlns:fx="http://javafx.com/fxml/1">
    <items>
        // ...
        <Label fx:id="oneOfMyLabels" text="myText" GridPane.columnIndex="2" GridPane.rowIndex="1" />
    </items>
</SplitPane>

现在,我在“主”控制器< code >应用程序中使用注入。MyMainController:

@FXML
private Label oneOfMyLabels;

如果我运行控制器,我会得到一个< code > Java . lang . nullpointerexception 异常,分别是一个< code > Java . lang . reflect . invocationtargetexception 异常。在调试模式下我发现,注入的< code>Label是< code>null!

现在,我的问题:无法从“主 fxml 文件”访问 MyMainController 包含的 fxml 文件的组件?我是否必须在每个 fxml 文件上使用自己的控制器,如果它是否包含在内?!

谢谢你的帮助!!


共1个答案

匿名用户

您需要为每个 FXML 文件设置不同的控制器,并且每个文件的 fx:id 注释元素将被注入到相应的控制器实例中。

包含FXML文件后,您可以通过在fx: include元素上设置fx:id属性,将包含文件的控制器注入包含文件的控制器:

“主”fxml文件:

<?import javafx.geometry.*?>
// ...

<BorderPane prefHeight="962" prefWidth="1280" xmlns="http://javafx.com/javafx/8.0.40" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.MyMainController">
    <center>
        <SplitPane dividerPositions="0.63" BorderPane.alignment="CENTER">
            <items>
                <fx:include fx:id="another" source="AnotherFile.fxml" />
                // ...
            </items>
        </SplitPane>
    </center>
    <top>
        // ...
    </top>
</BorderPane>

并且在“主控制器”中:

public class MyMainController {

    @FXML
    private AnotherController anotherController ;

    // ...
}

(规则是字段名是附加了"Controller"fx: id属性的值)。这里antherControllerantherFile.fxml的控制器类。

例如,现在您可以在“包含的控制器”中公开您需要访问的数据:

public class AnotherController {

    @FXML
    private Label oneOfMyLabels ;

    public StringProperty textProperty() {
        return oneOfMyLabels.textProperty();
    }

    public final String getText() {
        return textProperty().get();
    }

    public final setText(String text) {
        textProperty().set(text);
    }

    // ...
}

然后你的主控制器可以做一些事情,比如

anotherController.setText(...);

这当然会更新标签。这将保留封装,因此,如果选择使用另一个控件而不是标签,则这些更改不必传播到直接控制器之外。