我有一个UI,其中包含许多可以重用的组件;所以,我链接了一些. fxml
文件。我的父.fxml嵌入了这个:
<fx:include source="Child.fxml" fx:id="first">
<fx:include source="Child.fxml" fx:id="second">
Child.fxml
如下所示:
<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>
Parent.fxml
有一个定义的fx:controller=“ParentController”
。问题是,我如何设置/获取家长中每个孩子的数据。比如:
first.getLabel().setText("This is the first Label");
first.getComboBox().getValue();
second.getLabel().setText("This is the second Label");
...
请不要建议回答fist. get儿童().get(0)
等类似方法。
我知道我只能定义一个大的 .fxml
,然后给每个项目一个 id,但我想避免重复代码,我想将它们拆分为更小的组件,以便它更容易理解,我可以重用它们。
您可以将包含的FXML的控制器注入包含它们的FXML控制器中:
public class ParentController {
@FXML
private ChildController firstController ;
@FXML
private ChildController secondController ;
@FXML
private Pane childContainer ; // container holding the included FXMLs
// ...
}
这里我假设< code>Child.fxml声明了一个控制器类< code > FX:controller = " child controller " 。命名嵌套控制器字段的规则是,它们是所包含的FXML的< code>fx:id,并附加了< code >“Controller”。
在该控制器中定义适当的数据方法(允许直接访问控件本身通常是不好的做法):
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();
}
// ...
}
现在回到父控制器
,您所需要的只是
first.setDisplayText("This is the first Label");
first.getUserSelectedValue();
second.setDisplayText("This is the second Label");
等。
如果您需要在运行时动态包含Child. fxml
中定义的更多FXML实例,您只需要:
// modify resource name as needed:
FXMLLoader loader = new FXMLLoader(getClass().getResource("Child.fxml"));
Parent childUI = loader.load();
ChildController childController = loader.getController();
childContainer.getChildren().add(childUI);