1

I have 2 views: a main, and a subpane; and 2 respective controllers, each defined by an FXML file. A button pressed in main should result in an action in the subpane. Currently, I'm simply importing the subpane's fxml into the main one like so:

...
<BorderPane parameters=values>
   <center>
      <AnchorPane parameters=values>
         <fx:include fx:id="subPane" source="../../bin/view/SubPane.fxml" />
      </AnchorPane>
   </center>
</BorderPane>
...

which gives me access to the parameter "subPaneController" for free. However, I recently read this question where a new approach is presented. I would create a SubPaneController on the fly when needed using

FXMLLoader loader = new FXMLLoader(getClass().getResource("/view/SubPane.fxml"));
loader.load();
SubPaneController sc = loader.<SubPaneController>getController();

I am interested in using this approach as it seems more widely applicable (e.g. any controller could chat with any other). I have tried setting this up with my system, and it appears that this second method creates a new subPaneController, which renders this approach currently useless for me since I would need to manually tie it to the main view, which is what I thought the FXML files were for.

So, I have 2 very related questions. Can I get the already-instantiated controller? (Maybe I need to use a Singleton pattern or something?) And why is this technique better than importing FXMLs? (I have heard dependency injection can solve issues like this, but I'm not really sure how that works with FXML stuff. I'm not explicitly asking about that, though I would certainly be open to comments about it.)

Community
  • 1
  • 1
buggaby
  • 359
  • 2
  • 13

0 Answers0