【发布时间】:2022-02-19 10:49:55
【问题描述】:
我有一个有 40 个文本字段的程序。我想知道如何在每个和 setText 上循环。每个 textFields 已经有不同的 fxid。请帮忙!我想简洁地编码。
【问题讨论】:
-
一种选择是使用这种方法:stackoverflow.com/a/34470630/2991525
我有一个有 40 个文本字段的程序。我想知道如何在每个和 setText 上循环。每个 textFields 已经有不同的 fxid。请帮忙!我想简洁地编码。
【问题讨论】:
您需要一个List 来跟踪每个TextField。您的问题不包含任何代码,因此很难确定在您的情况下执行此操作的最简单方法,但有几个选项。
TextField 控件都包含在同一个布局容器中,例如VBox 或FlowPane,您可以使用该容器的子项列表:@987654326 @
List:如果您的所有TextFields 都有fx:id,则将它们添加到List:list.add(textField)现在您有了列表,只需使用迭代器或简单的 for 循环遍历它们:
容器子代:
for (Node node : root.getChildren()) {
// If you're certain all the children ARE TextFields, cast the node now
((TextField) node).setText("Yay for text!");
}
您自己的列表:
// Create a List to track all the TextFields
List<TextField> textFieldList = new ArrayList<>();
// Add some TextFields to the list
for (int i = 0; i < 20; i++) {
textFieldList.add(new TextField());
}
// Now iterate over the list of TextFields and set their text
for (TextField textField :
textFieldList) {
textField.setText("Yay for text again!");
}
【讨论】: