I have a lot of Objects with names a1, a2, a3, ... I need to put them into List, so that it was simplier to work with them, will I do it somehow with loop?
My attempt was:
List<SomeObject> list = new LinkedList<SomeObject>();
for (int i=0; i<1000; i++){
String varName = "a"+i;
list.add((SomeObject) varName);
}
Does anyone have suggestions in this case? Create variables inside loop is not a solution, because they are a part of .fxml document. Or give me an advice how to create that with loop, for it create lines in .fxml parallel to adding in loop new objects.
To be more understandable .fxml file looks like
<SomeObject fx:id="a1" *other props* />
<SomeObject fx:id="a2" *other props* />
<SomeObject fx:id="a3" *other props* />
<SomeObject fx:id="a4" *other props* />
Thanks a lot in advice!
Personally I'd prefer the other possibility, but just for the sake of completness:
You can also access
Object
s created by theFXMLLoader
by thefx:id
attribute after loading, usingFXMLLoader.getNamespace()
:Example
namespace.fxml
Loading
Prints the text from the
Text
element in the fxml (i.e.42
).Of course you do not get access to the
FXMLLoader
instance by default in the controller, which means with this approach you need to pass the information to the controller yourself, if it's required there.If you have that many items, it's probably best to initialize them using Java, rather than using FXML. For example, instead of:
and a controller
I would do
and
As a variation on this idea, consider defining a custom component:
Now in your FXML you do
and in your controller
You need to jump through a couple of hoops if you want to use a custom class like that in Scene Builder. See Adding a custom component to SceneBuilder 2.0
If you really want to define all those controls in FXML, which would be a maintenance nightmare imo, you can use reflection to access the variables. I don't recommend this, not just because it's hard to maintain, but also because reflection by its nature is error-prone (no compile-time checking) and complex.
But you could do
You may prefer to put your objects into the list in the fxml directly:
and access it in the controller as:
if you are not accessing each SomeObject individually you can drop
fx:id
s for them. For more info about fxml features refer to Introduction to FXML.