How to access parent member controller from child controller

别等时光非礼了梦想. 提交于 2019-11-29 07:52:56

Just pass the reference from the parent controller to the child controller in the parent controller's initialize() method:

ParentController.java:

public class ParentController {

    @FXML
    private ChildController childController ;

    private User user ;

    public void initialize() {
        user = ...;
        childController.setUser(user);
    }
}

ChildController.java:

public class ChildController {

    private User user ;

    public void setUser(User user) {
        this.user = user ;
    }
}

You can also do this with JavaFX Properties instead of plain objects, if you want binding etc:

ParentController.java:

public class ParentController {

    @FXML
    private ChildController childController ;

    private final ObjectProperty<User> user = new SimpleObjectProperty<>(...) ;

    public void initialize() {
        user.set(...);
        childController.userProperty().bind(user);
    }
}

ChildController.java:

public class ChildController {

    private ObjectProperty<User> user = new SimpleObjectProperty<>();

    public ObjectProperty<User> userProperty() {
        return user ;
    }
}

As usual, the parent fxml file needs to set the fx:id on the fx:include tag so that the loaded controller is injected to the

<fx:include source="/path/to/child/fxml" fx:id="child" />

the rule being that with fx:id="x", the controller from the child fxml will be injected into a parent controller field with name xController.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!