1

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.

DVarga
  • 21,311
  • 6
  • 55
  • 60
Geta92
  • 13
  • 3

1 Answers1

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();
DVarga
  • 21,311
  • 6
  • 55
  • 60
  • Thank you very much! This worked really well for my tabs. I'm only having an issue if I want to do the same when I create a new window. Trying to access the controller there will always result in a nullPointerException. I'm adding a new reply once I understand the error a little better. – Geta92 May 13 '16 at 10:15
  • 1
    If the answer fixed your problem, could you accept it and vote it up? This would close this question - then you can create another one for another problem. This makes the question clear. Thanks :) – DVarga May 13 '16 at 10:20
  • Turns out the problem is that I need to access the controller inside the initialize() method, but it will still be null at that point since the reference can only be added after that. EDIT: Solved that one myself. Thanks ;) – Geta92 May 13 '16 at 10:24