如果您有这么多项目,最好使用 Java 来初始化它们,而不是使用 FXML。例如,而不是:
<FlowPane fx:id="container" minWidth="..." minHeight="...">
<Label fx:id="label1" text="Label 1"/>
<Label fx:id="label2" text="Label 2"/>
<Label fx:id="label3" text="Label 3"/>
<!-- ... -->
<Label fx:id="label1000" text="Label 1000"/>
</FlowPane>
还有一个控制器
public class Controller {
@FXML
private FlowPane container ;
@FXML
private Label label1 ;
@FXML
private Label label2 ;
// ...
@FXML
private Label label1000 ;
// ...
}
我愿意
<FlowPane fx:id="container" minWidth="..." minHeight="...">
</FlowPane>
和
public class Controller {
@FXML
private FlowPane container ;
private List<Label> labels ;
public void initialize() {
labels = new ArrayList<>();
for (int i = 1; i <= 1000; i++) {
Label label = new Label("Label "+i);
labels.add(label);
container.getChildren().add(label);
}
}
}
作为这个想法的一个变体,考虑定义一个自定义组件:
public class LabelFlow extends FlowPane {
private List<Label> labels ;
public LabelFlow(@NamedArg("numLabels") int numLabels) {
labels = new ArrayList<>();
for(int i = 1 ; i <= numLabels ; i++) {
Label label = new Label("Label "+i);
labels.add(label);
}
getChildren().addAll(labels);
}
public List<Label> getLabels() {
return Collections.unmodifiableList(labels);
}
}
现在在你的 FXML 中你做
<LabelFlow fx:id="labelFlow" numLabels="1000"/>
在你的控制器中
public class Controller {
@FXML
private LabelFlow labelFlow ;
public void initialize() {
for (Label label : labelFlow.getLabels()) {
// do whatever you need with label....
}
}
}
如果您想在 Scene Builder 中使用类似的自定义类,则需要跳过几个环节。见Adding a custom component to SceneBuilder 2.0
如果您真的想要在 FXML 中定义所有这些控件,这将是 imo 维护的噩梦,您可以使用反射来访问变量。我不推荐这样做,不仅因为它难以维护,还因为反射本质上容易出错(没有编译时检查)且复杂。
但你可以这样做
public class Controller {
@FXML
private FlowPane container ;
@FXML
private Label label1 ;
@FXML
private Label label2 ;
// ...
@FXML
private Label label1000 ;
private List<Label> labels ;
public void initialize() throws Exception {
labels = new ArrayList<>();
for (int i = 1; i <= 1000; i++) {
Field field = getClass().getDeclaredField("label"+i);
boolean wasAccessible = field.isAccessible();
field.setAccessible(true);
Label label = (Label) field.get(this);
field.setAccessible(wasAccessible);
labels.add(label);
}
}
}