gpt4 book ai didi

Javafx: 链接 fx:id-s

转载 作者:行者123 更新时间:2023-12-01 20:18:07 25 4
gpt4 key购买 nike

我有一个包含许多组件的 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 的 Controller 注入(inject)到包含它们的 FXML 的 Controller 中:

public class ParentController {

@FXML
private ChildController firstController ;
@FXML
private ChildController secondController ;

@FXML
private Pane childContainer ; // container holding the included FXMLs

// ...
}

这里我假设 Child.fxml 声明了一个 Controller 类 fx:controller="ChildController"nested controllers 的字段命名规则是他们是fx:id of the included FXML with "Controller" appended .

在该 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();
}

// ...
}

现在回到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);

关于Javafx: 链接 fx:id-s,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45371703/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com