FXMLLoader get controller returns null

给你一囗甜甜゛ 提交于 2019-12-24 02:25:10

问题


I have a recursive case of FXML loading needed here.

If I choose to View an Objective, it takes me to another instance of the screen that loads a list of Strategy objects. If I choose to view a Strategy, it takes me to another instance of the screen that loads a list of Tactic objects. If I view a Tactic, it takes me to another instance of the screen that loads a list of Task objects.

Naturally, I decided to use a base controller class, ViewChildItemController to handle inheritance. Then I extended from it ViewObjective, ViewStrategy, and ViewTactic. (ViewTask makes no sense because a Task is the very lowest level item with no children).

The problem is, when I use loader.loadController(), the method returns null.

FXMLLoader loader = new FXMLLoader(this.getClass()
        .getResource(ScreenPaths.VIEW_PLAN_ITEM));
Parent root = null;
try {
    root = loader.load();
} catch (IOException e) {
}
ViewObjectiveController ctrl = loader.getController();//Return null? Why?
ObservableList<Strategy> childItems = childItemsTableView.
        getSelectionModel().getSelectedItem().getChildPlanItems();
ctrl.initValues(childItems);
DialogPopup.showNode(root);

Could it be that the base FXML being loaded is hooked to the ViewChildItemController? Do I have to create several copies of the FXML and hook the controllers separately to each ViewObjectiveController, ViewStrategyController, etc? It doesn't make much sense to do.

I could try loader.setController(), but I'm not sure if the @FXML attributes will be mapped again.


回答1:


Turns out all I had to do was treat the controller as "dynamic".

That is, set the controller BEFORE loading the root.

@Override
protected void viewChildItem() {
    FXMLLoader loader = new FXMLLoader(this.getClass()
            .getResource(ScreenPaths.VIEW_PLAN_ITEM));
    ViewTacticController ctrl = new ViewTacticController();
    loader.setController(ctrl);
    Parent root = null;
    try {
        root = loader.load();
    } catch (IOException e) {
    }
    ObservableList<Task> childItems = childItemsTableView.
            getSelectionModel().getSelectedItem().getChildPlanItems();
    ctrl.initValues(childItems);
    DialogPopup.showNode(root);
}


来源:https://stackoverflow.com/questions/25534480/fxmlloader-get-controller-returns-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!