JAVAFX - FXML - Access Loaded FXML Controls from Parent Controller


Question

Here is what I am trying to accomplish.

/Package A/
/Package A/ApplicationController.java
/Package A/Application.fxml

In my Application.fxml file I have a button, and when that button is clicked it loads the following "MyGrid.fxml" file.

/Package B/
/Package B/MyGrid.fxml (has a label #mygridlabelid

The code I am using is:

ContentPane.getChildren().add((Node)FXMLLoader.load(getClass().getResource("/Package B/MyGrid.fxml")));

But the problem is.. even though I am loading the MyGrid.fxml file from the ApplicationController, I cannot access #mygridlabelid from the ApplicationController file. I defined @FXML label mygridlabelid in the ApplicationController.java file, but it doesn't get instantiated :(

How can I do that? Any tricks or hacks around it?

1
0
7/23/2013 1:40:42 PM

Accepted Answer

I managed to solve the problem by doing the following... and make sure that the .fxml file does not have fx:controller set. Or else you will run into "Controller value already specified."

    FXMLLoader loader = new FXMLLoader(getClass().getResource("/your.fxml"));
    loader.setController(this);
    try {
        ContentPane.getChildren().add((Node)loader.load());
    } catch (IOException e){
        System.out.println(e.getMessage());
    }
2
7/23/2013 1:41:00 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon