FXMLLoader cannot find running controller instance and creates new one

佐手、 提交于 2020-01-16 07:07:52

问题


I'm a newcomer when it comes to JavaFX and I recently encountered a problem which really confuses me alot. I'm using a class called "MainController" which controlls an FXML-File containing a TabPane. Each tab is controlled by another controller. But there is one situation in which a tab needs to be deleted, so I need access to the MainController instance to remove the currently active tab from the pane.

Whenever I'm using this code to get an instance of the currently running MainController, I instead get a completely new instance with all of its components set to their default values.

The code is:

FXMLLoader loader = new FXMLLoader(getClass().getResource("Main.fxml"));
loader.load();
MainController controller = loader.getController();
controller.closeCurrentTab();

 

protected void closeCurrentTab() {
    tabPane.getTabs().remove(tabPane.getSelectionModel().getSelectedIndex());
}

I'm currently using a static reference to the controller to access it since it is the only solution that works for me. But I know that this is highly unprofessional and I really want to avoid that.

I hope somebody knows what's wrong here.


回答1:


You should ensure that you have a reference for your main controller at the point where you want to use it. I guess it is one of the "child" controllers (most probably the controller of the current tab).

Therefore if you would have a property in this class that stores the reference for your main controller, your problem would be solved.

I guess you initialize this "child" controller from the main controller like:

FXMLLoader loader = new FXMLLoader(getClass().getResource("TabController1.fxml"));
loader.load();

So here you could do:

TabController controller = loader.getController();
controller.mainControllerProperty.set(this);

Where mainControllerProperty is defined in TabController like:

ObjectProperty<MainController> mainControllerProperty = new SimpleObjectProperty();


来源:https://stackoverflow.com/questions/37205187/fxmlloader-cannot-find-running-controller-instance-and-creates-new-one

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