this page from oracle上说明了如何在主控制器中注入子控制器:

<VBox fx:controller="com.foo.MainController">
...
    <fx:include fx:id="dialog" source="dialog.fxml"/>
...
</VBox>

public class MainController extends Controller {
    @FXML private Window dialog;
    @FXML private DialogController dialogController;

    ...


现在,我想知道如何从子控制器(在本例中为MainController)到达DialogController实例。

感谢您的帮助!

最佳答案

我建议不要这样做。如果您的DialogController依赖于您的MainController,那么它不能独立于MainController使用,这会在两者之间增加不必要的耦合(即破坏封装)。

MainController中的某些状态更改时,您可能只希望DialogController中发生某些事情。因此,您应将该状态公开为DialogController中的可观察属性,并从主控制器进行观察:

public class DialogController {

    private final ReadOnlyObjectWrapper<Person> selectedPerson = new ReadOnlyObjectWrapper<>();

    public ReadOnlyObjectProperty<Person> selectedPersonProperty() {
        return selectedPerson.getReadOnlyProperty();
    }

    public final Person getSelectedPerson() {
        return selectedPersonProperty().get();
    }

    @FXML
    private Button okButton ;

    public void initialize() {
        okButton.setOnAction(selectedPerson.set(new Person(...)));
    }
}


然后

public class MainController extends Controller {
    @FXML private Window dialog;
    @FXML private DialogController dialogController;

    public void initialize() {
        dialogController.selectedPersonProperty().addListener((obs, oldPerson, newPerson) -> {
            // ... whatever you need to do here with new data when OK is pressed in dialog...
        });
    }
}


如果您确实要从MainController访问DialogController,则可以按照注释中的建议进行操作,方法是“手动”将MainController注入DialogController。但是,这是糟糕的设计,imo。

public class DialogController {

    // Ugh. DialogController cannot be used outside the context where
    // MainController exists.
    private MainController mainController ;

    @FXML
    private Button okButton ;

    public void setMainController(MainController mainController) {
        this.mainController = mainController ;
    }

    public void initialize() {
        okButton.setOnAction(e -> {
            if (mainController != null) {
                mainController.doSomething();
            }
        });
    }
}




public class MainController {

    @FXML
    private DialogController dialogController ;

    public void initialize() {
        dialogController.setMainController(this);
    }

    public void doSomething() {
        // ...
    }
}

关于java - JavaFX-从子 Controller 到达主 Controller ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32987195/

10-09 19:47