4

Is possible to connect two FXML (JavaFX) files to one controller? I can't do this with changing "fx:controller" in each FXML file...

Any ideas?

phil652
  • 1,484
  • 1
  • 23
  • 48
Balu
  • 43
  • 1
  • 1
  • 5
  • 1
    It's possible to use the same controller class for multiple FXML files, but your code will be really hard to follow, and it's a very bad idea. (Also note that using the `fx:controller` attribute, you will have a different controller *instance* each time you call `FXMLLoader.load(...)`, even if you use the same controller *class*.) Use a different controller class for each FXML file. – James_D May 26 '15 at 17:52
  • 1
    There is never any need for multiple FXML files to share the same controller. If you need to communicate between the controllers, use the techniques described [here](http://stackoverflow.com/questions/14187963/passing-parameters-javafx-fxml). – James_D May 26 '15 at 20:20

2 Answers2

8

Yes, you can do this. Although, it can be done, I do not recommend this approach.

Don't place a fx:controller attribute in either FXML. Create a new controller and set the same controller into separate FXMLLoader instances.

CustomerDialogController dialogController = 
    new CustomerDialogController(param1, param2);

FXMLLoader summaryloader = new FXMLLoader(
    getClass().getResource(
        "customerSummary.fxml"
    )
);
summaryLoader.setController(dialogController);
Pane summaryPane = (Pane) summaryLoader.load();

FXMLLoader detailsLoader = new FXMLLoader(
    getClass().getResource(
        "customerDetails.fxml"
    )
);
detailsLoader.setController(detailsController);
Pane detailsPane = (Pane) detailsLoader.load();

SplitPane splitPane = new SplitPane(
    summaryPane, 
    detailsPane
);

I want to create one controller, because I have problem with sending data beetwen controlers

IMO using a shared controller just to share data is not the preferred solution for this.

Instead, either share the data between multiple controllers, for examples of this see:

There is a further example here:

Even better, see:

jewelsea
  • 150,031
  • 14
  • 366
  • 406
2

Use the fx:root construct instead of fx:controller. It is explained in the Custom Components section of the FXML docs. I have used it in this example for my students if you want a bigger code example.

Using this approach, creating views and controllers will be a lot easier and flexible. You will be able to share data between and connect controllers like you would any other objects in your application (for example: by passing data via the constructor or setter methods).

If you're using SceneBuilder you'll simply need to remove the controller reference and check the box "Use fx:root". Then rework your code as shown in the examples.

Steven Van Impe
  • 1,153
  • 8
  • 15