JavaFX在父FXML中更改标签

时间:2015-08-11 20:09:16

标签: javafx-8

  • 父文件:FXML-A&控制器-A
  • 子文件:FXML-B&控制器-B

我有以上层次结构,其中FXML-B位于FXML-A之上,使用" parent_stackPane从Controller-A加载。 getChildren()。setAll (child_fxmlLoader_load)"一种方式。因此FXML-A是FXML-B的父母。

无论如何,我可以从子控制器B更改父FXML-A中标签的文本吗?

1 个答案:

答案 0 :(得分:0)

StringProperty中定义ControllerB

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...
}

现在,当您在setText(...)中致电ControllerB时,它会更新标签中的文字。