JavaFX从FXML子访问父控制器类

使用JavaFX作为应用程序,我有一个Main.fxml文件,里面有一些fxml子文件.

我想从子控制器访问Main.fxml的MainController类.

我将尝试用一个例子更好地解释:

MainFxml:

    <HBox fx:controller="MainController.java">
        <fx:include source="child.fxml"/>
    </HBox>

MainController:

    public class MainController implements Initializable {
            private String string;
            public void setString (String string) {
                    this.string = string;
            }

ChildFxml:

    <HBox fx:id="child" fx:controller="ChildController.java">
        <Button text="hello" onAction="#selectButton"></Button>
    </HBox>

ChildController:

    public class ChildController implements Initializable {
            @FXML HBox child;
            @FXML Button button;
            @FXML
            public void selectButton (ActionEvent event) {
                // here call MainController.setString("hello");
            }

我尝试了this solution found on StackOverflow,但我需要获取已经加载的Main.fxml的Controller引用.
是否有任何方法可以从特定的窗格启动Controller?
就像是:

    // child.getParent().getController();
如果您将fx:id分配给< fx:include>标记,FXMLLoader尝试将包含的fxml的控制器注入名为< fx:id> Controller的字段.您可以在initialize方法中将MainController引用传递给子控制器:

<HBox fx:controller="MainController.java">
    <fx:include fx:id="child" source="child.fxml"/>
</HBox>

MainController

@FXML
private ChildController childController;

@Override
public void initialize(URL url, ResourceBundle rb) {
    childController.setParentController(this);
}

ChildController

private MainController parentController;

public void setParentController(MainController parentController) {
    this.parentController = parentController;
}

@FXML
private void selectButton (ActionEvent event) {
    this.parentController.setString("hello");
}

但是,将ChildController与父级保持独立是更好的做法.这可以通过在ChildController中提供一个StringProperty来完成,该StringProperty设置为父应该显示的值.

ChildController

private final StringProperty value = new SimpleStringProperty();

public StringProperty valueProperty() {
    return value;
}

@FXML
private void selectButton (ActionEvent event) {
    value.set("hello");
}

ParentController

@Override
public void initialize(URL url, ResourceBundle rb) {
    childController.valueProperty().addListener((observable, oldValue, newValue) -> setString(newValue));
}
https://stackoverflow.com/questions/44807580/javafx-access-parent-controller-class-from-fxml-child

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:JavaFX从FXML子访问父控制器类