Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
749 views
in Technique[技术] by (71.8m points)

javafx 8 - How to access parent member controller from child controller

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...