I have two FXML files. The first describes the first pane to show up, which contains a tab pane, a menu and a menu item, which is supposed to open a new tab in the tab pane and draw a new set of Nodes in it. This is the code:
public class Main extends Application {
private Pane mainRoot;
private Pane secondaryRoot;
@Override
public void start(Stage primaryStage) {
try {
mainRoot = (Pane) ResourceLoader
.load("MainFXML.fxml");
secondaryRoot = (Pane) ResourceLoader.load(("SecondaryFXML.fxml"));
Scene scene = new Scene(mainRoot);
primaryStage.setScene(scene);
primaryStage.show();
thisMain = this;
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
private static Main thisMain;
public static Main getMain() {
return thisMain;
}
public Pane getSecondaryRootPane() {
return secondaryRoot;
}
Then I have a single controller associated to both FXML files. So, it has the tab pane as a FXML-annotated field. Furthermore, it handles the click event on the menu item, which is the one creating the new tab:
public class GUIController {
@FXML
private TabPane tabPane;
public void newTabRequest(Event e) {
// create the new tab
Tab newTab = new Tab("New tab");
// set the content of the tab to the previously loaded pane
newTab.setContent(Main.getMain().getSecondaryRootPane());
// add the new tab to the tab pane and focus on it
tabPane.getTabs().add(newTab);
tabPane.getSelectionModel().select(newTab);
initializeComboBoxValues(); // HERE I HAVE A PROBLEM
}}
Last line of the controller invokes a method, whose code is as follow:
private void initializeComboBoxValues() {
myComboBox.getItems().add(MyEnum.myEnumValue1);
myComboBox.getItems().add(MyEnum.myEnumValue2);
}
and I have a field @FXML ComboBox having the same name as the corresponding component declared in the FXML and that I am trying to fill up with values. The issue is that myComboBox results null. Where am I wrong? Where am I designing it wrong?
If it can help, I want to make this point: I created and added a test button in the new tab. The event associated to this button invokes the same initializeComboBoxValues method. Well, that works (given I remove its invocation from the newTabRequest handler, so to avoid the NPE).