Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One controller to 2 fxmls (JavaFX)

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?

like image 381
Balu Avatar asked Jan 09 '23 07:01

Balu


1 Answers

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:

  • Passing Parameters JavaFX FXML

There is a further example here:

  • JavaFX8 list bindings similar to xaml

Even better, see:

  • Applying MVC With JavaFx
  • https://edencoding.com/mvc-in-javafx/
like image 136
jewelsea Avatar answered Feb 27 '23 21:02

jewelsea