如何从子控制器访问父成员控制器

如何从子控制器访问父成员控制器

本文介绍了如何从子控制器访问父成员控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题类似于,但我需要访问父成员(不是控制)。我不知道是否可以不使用依赖注入。

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.

例如,我有一个Parent,有一个成员调用User,我需要从子进程控制器到用户。

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

推荐答案

只需将父控制器的引用传递给父控制器的 initialize()方法:

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

ParentController.java:

ParentController.java:

public class ParentController {

    @FXML
    private ChildController childController ;

    private User user ;

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

ChildController.java:

ChildController.java:

public class ChildController {

    private User user ;

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

您也可以使用JavaFX Properties对象,如果你想绑定等:

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

ParentController.java:

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:

ChildController.java:

public class ChildController {

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

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

像往常一样,父fxml文件需要设置在 fx:include 标签上的 fx:id ,以便将加载的控制器注入

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" />

规则是 fx:id =x,来自子fxml的控制器将注入到名为 xController 的父控制器字段中。

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.

这篇关于如何从子控制器访问父成员控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 12:45