JavaFX 更改父 FXML 中的标签

JavaFX changing a label in parent FXML

我有上面的层次结构,其中 FXML-B 在 FXML-A 之上,使用 "parent_stackPane.getChildren().setAll(child_fxmlLoader_load)" 一种方式从 Controller-A 加载。所以 FXML-A 是 FXML-B 的父级。

我是否可以从子 Controller-B 更改父 FXML-A 中的标签文本?

ControllerB中定义一个StringProperty:

public class ControllerB {

    private StringProperty text = new SimpleStringProperty();

    public StringProperty textProperty() {
        return text ;
    }

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

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

    // other code as before ...

}

当你在 ControllerA 中加载第二个 fxml 时,将标签的文本绑定到 textProperty:

public class ControllerA {

    @FXML
    private Label label ;

    @FXML
    private StackPane parentStackPane ;

    @FXML
    private void someHandlerMethod() throws Exception {
        FXMLLoader loader = new FXMLLoader(getClass().getResource("FxmlFileB.fxml"));
        Parent rootB = loader.load();
        ControllerB controllerB = loader.getController();
        label.textProperty().unbind();
        label.textProperty().bind(controllerB.textProperty());
        parentStackPane.getChildren().setAll(rootB);
    }

    // other code as before...
}

现在,当您在 ControllerB 中调用 setText(...) 时,它会更新标签中的文本。