bashoogzaad
bashoogzaad

Reputation: 4781

Access elements of loaded FXML in Parent Controller

I currently have the following situation:

I have created a FXML file backed up by a FXML Controller. The screen consists of a sidebar and a child holder. When I click on an element in the sidebar, I load an additional FXML file in the child holder, like this:

childHolder.getChildren().addAll(FXMLLoader.load(getClass().getResource("SidebarItem1.fxml")));

This works fine. But I want to access some elements of the loaded FXML in the Controller of the Parent Controller. I just initialized the elements of the child FXML after I loaded it.

I already looked at this question: JAVAFX - FXML - Access Loaded FXML Controls from Parent Controller, but when I do it like that, I still get an error:

FXMLLoader loader = new FXMLLoader(getClass().getResource("SidebarItem1.fxml"));
loader.setController(this);
childHolder.getChildren().addAll(loader.load());

someChildTextField.setText("Some text");

I have given someChildTextField a fx:id and I have placed it on top of the initialize like this:

@FXML public TextField someChildTextField;

Still, I get a NullpointerException, so I assume it can still not find the control.

Does anyone know how to access elements of a loaded FXML in the Parent Controller?

Upvotes: 3

Views: 6349

Answers (1)

James_D
James_D

Reputation: 209694

I can't see any reason your approach doesn't work; I mocked something similar up and it worked just fine. This is an unusual approach, though, as you are using the same object as a controller for two separate FXML files.

I would recommend using one controller for each FXML. So you could do something like

public class SidebarItem1Controller {

    @FXML
    private TextField someTextField ;

    public void setText(String text) {
        someTextField.setText(text);
    }

}

and then from your parent controller just do

FXMLLoader loader = new FXMLLoader(getClass().getResource("SidebarItem1.fxml"));
childHolder.getChildren().add(loader.load());
SideBarItem1Controller childController = loader.getController();
childController.setText("Some Text");

Set the controller in your SideBarItem1.fxml file the usual way, with fx:controller = com.example.SidebarItem1Controller"

Upvotes: 6

Related Questions