r/JavaFX • • 2d ago

An interesting piece of info I learned about nested controllers

When you nest an fxml layout file inside another with fx:include, the controller of the containing (outer) fxml layout gets a reference to the controller of the included layout with a naming convention of: root+Controller:
This is not very clearly explained in the official docs (here).

I use -ctrl as a naming convention and just included the controller with its original name:
@ FXML

NestedCtrl nestedCtrl

@ FXML

VBox nestedRoot;

Turned out: No. it has to be nestedRootController in this case. Just wanted to share this. Cheers!

10 Upvotes

6 comments sorted by

2

u/tankmatesaquaponics 2d ago

Can you provide a working code snippet we can try ? I didn't know we can officially nest controllers. I always passed the reference explicitly

3

u/No-Security-7518 2d ago

Oh it's in the link (points right to the snippet, you won't need to scroll).

And here's a tip I want to share btw, in case someone is where I'm at:

Passing parameters through setters is better than to constructors directly. Because as the scene graph grows, you'll have to reload data on a nested controller.

For example, if you add some item to a list on a form, when you move from the form, to the table/list/container of such items.

For example:

//instead of this:

UserController userController = new UserController(userDao);

//loading the root as usual...

//specify userController directly to users.fxml then make UserController a field:

@ FXML

UserController userViewController;

//in a method that reloads users (e.g. after adding/deleting/modifying users):

userViewController.refreshUsers();

2

u/OddEstimate1627 2d ago

I would inject a class with state exposed as javafx properties that UI elements can bind to. That way the state can be changed without keeping references to any part of the UI.

2

u/No-Security-7518 2d ago

That's neat, yeah. I would too. But I need to reuse most if not all of the data objects in Android or non-javaFX projects. So I need them to be pure Java. And a wrapper felt like too much of a hassle.