FXMLLoader cannot find running controller instance

2019-08-14 06:18发布

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条回答
走好不送
2楼-- · 2019-08-14 06:28

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();
查看更多
登录 后发表回答