How to access parent member controller from child

2019-01-26 16:01发布

问题:

This question is similar to this, but I need to access parent member (not control). I don't know if is possible to do without using Dependency Injection.

For example, I have a Parent with have a member calls User, I need to access from child controller to User.

回答1:

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.