r/JavaFX • u/nskarthik_k • Jun 04 '22
Help Javafx 18 dynamic loop in fxml
Spec Jdk17, Jfx18, WinO/s
Question : I need to create a for-loop in fxml to create radiobuttons on request from controller
ex:
List<String> lstdynamicRadiobutt = 1 or 2 or 3 or 5 or 10 ..... // in controller
for( String radiox : lstdynamicRadiobutt ){ //in gui fxml
//radiobuttons in fxml for each radiox
}
Appreciate for the solution....
1
u/OddEstimate1627 Jun 04 '22
You would create a reference to the parent container and then build that part dynamically in the controller. Something like:
Controller:
@FXML
Pane buttonPane;
public void initialize() {
for( String name: radioButtonNames){
buttonPane.getChildren().add(new RadioButton(name));
}
}If you have a max number of options you can also define them all in FXML and hide them as appropriate.
1
u/hamsterrage1 Jun 04 '22
Then your layout is split between two places: the FXML file and the FXMLController.
1
u/OddEstimate1627 Jun 08 '22
same split as always:
static layout => FXML
dynamic behavior => Controller
There is an
fx:scriptelement, but I've never used it and wouldn't recommend adding complex behavior to an XML file. IMO that sounds like a maintenance nightmare.
3
u/KapFlagon Jun 04 '22
You can't create loops or logic using FXML, it's purely used for organising layout, and can't contain logic.
However, you can create logic to create a view using pure Java code. I suggest checking out this tutorial from Pragmatic Coding for some more info on how to do that.