How to access parent member controller from child controller

后端 未结 1 594
独厮守ぢ
独厮守ぢ 2020-12-18 07:02

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 exampl

相关标签:
1条回答
  • 2020-12-18 07:40

    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.

    0 讨论(0)
提交回复
热议问题