java - Javafx: link fx:id-s -
i have ui many components reused ; so, have few .fxml
files linked. parent .fxml embeds this:
<fx:include source="child.fxml" fx:id="first"> <fx:include source="child.fxml" fx:id="second">
the child.fxml
looks this:
<hbox xmlns="http://javafx.com/javafx" xmlns:fx="http://javafx.com/fxml"> <label fx:id="label"/> <combobox fx:id="combobox"/> <textfield fx:id="firsttextfield"/> <tableview fx:id="secondtextfield"/> </hbox>
the parent.fxml
has defined fx:controller="parentcontroller"
. question is, how can set/get data each individual child in parent. like:
first.getlabel().settext("this first label"); first.getcombobox().getvalue(); second.getlabel().settext("this second label"); ...
please don't suggest answer fist.getchildren().get(0)
and others similar methods.
i know can define 1 big .fxml
, , give every single item id, want avoid duplicate code, , want split them in smaller components may become more understandable, , can reuse them.
you can inject controllers included fxml controller fxml including them:
public class parentcontroller { @fxml private childcontroller firstcontroller ; @fxml private childcontroller secondcontroller ; @fxml private pane childcontainer ; // container holding included fxmls // ... }
here assuming child.fxml
declares controller class fx:controller="childcontroller"
. rule naming fields nested controllers fx:id
of included fxml "controller"
appended.
define appropriate data methods in controller (it bad practice allow direct access controls themselves):
public class childcontroller { @fxml private label label ; @fxml private combobox<string> combobox ; // etc... public void setdisplaytext(string text) { label.settext(text); } public string getuserselectedvalue() { return combobox.getvalue(); } // ... }
and in parentcontroller
need
first.setdisplaytext("this first label"); first.getuserselectedvalue(); second.setdisplaytext("this second label");
etc.
if need include more instances of fxml defined in child.fxml
dynamically @ runtime, need:
// modify resource name needed: fxmlloader loader = new fxmlloader(getclass().getresource("child.fxml")); parent childui = loader.load(); childcontroller childcontroller = loader.getcontroller(); childcontainer.getchildren().add(childui);
Comments
Post a Comment