I have a Pane component stored in a fxml file. I'm importing this component to another Scene, and I want this component to show with auto-generated information. So I searched this exact question and I found this: Passing parameters to a controller when loading an FXML. This what they do:
private void addReservation(Reservation r) {
try {
FXMLLoader fxmloader = new FXMLLoader(getClass().getResource("/views/item_reserva.fxml"));
Pane client = (Pane) fxmloader.load();
Item_reservaController controller = fxmloader.<Item_reservaController>getController();
controller.init(r);
flowPane.getChildren().add(client);
} catch (IOException ex) {
ex.printStackTrace();
}
}
I'm loading the component to the Parent type in this case Pane. And then I'm calling its controller and initializing the components and finally showing the Pane inside a Flowpane.
This is what the init method does:
public void init(Reservation r) {
this.reservation = r;
labelCountry = new Label(r.getClients().getFirst().getCountry());
labelRoom = new Label(Integer.toString(r.getRooms().size()));
labelClient = new Label(Integer.toString(r.getClients().size()));
}
I guess that the problem is related with that the object I'm drawing is not the same as the controller I'm changing, so it wont change the information inside the real components.
Since the init
method is called after loading the fxml, it's unlikely that the Label
s created in that method are added to the scene.
And no the labels are already defined in the fxml file.
Since the scene already contains the appropriate Label
s, use those Label
s instead of creating new ones. If the Label
s are sucessfully injected to the controller, just use setText
to assign the content:
public void init(Reservation r) {
this.reservation = r;
labelCountry.setText(r.getClients().getFirst().getCountry());
labelRoom.setText(Integer.toString(r.getRooms().size()));
labelClient.setText(Integer.toString(r.getClients().size()));
}