我的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.getChildren().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
// ...
}
在这里,我假设
Child.fxml
声明了一个控制器类fx:controller="ChildController"
。命名nested controllers字段的规则是它们是fx:id
of the included FXML with "Controller"
appended。在该控制器中定义适当的数据方法(通常不建议允许直接访问控件本身):
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();
}
// ...
}
现在回到
ParentController
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);