Java:如何将动态数量的参数传递给方法
Java: How to pass a dynamic amount of arguments to a method
我正在编写一个 JavaFX 应用程序,我需要使用其 [=14] 添加 n 个 TextField
对象到 GridPane
中的一行=] 方法。 addRow
接受任意数量的参数,但它接收的 TextField
个对象的数量不是硬编码的。例如,
GridPane gp = new GridPane();
ArrayList<TextField> tf = new ArrayList<>();
for (int i = 0; i < user_entered_number; i++) {
tf.add(new TextField());
}
gp.addRow(row_index, /* all elements in tf*/);
我希望使用 allRow
方法将所有生成的 TextField
对象包含在 row_index
的 GridPane
行中。
如果这是可能的,我该怎么做?
GridPane.addRow(...)
method 采用 int
(行索引)和 Node
的可变参数。您可以为 varargs 参数传递一个数组,这样您就可以
gp.addRow(row_index, tf.toArray(new Node[0]));
或者,首先创建一个数组而不是列表:
GridPane gp = new GridPane();
TextField[] tf = new TextField[userEnteredNumber];
for (int i = 0; i < userEnteredNumber; i++) {
tf[i] = new TextField();
}
gp.addRow(row_index, tf);
我不确定我是否正确理解你的问题。是否要将 tf ArrayList 中的所有元素添加为 addRow() 方法中的参数?
addRow() 方法将可变参数作为参数。您是否尝试将 ArrayList 转换为数组,然后将其传递给方法?
TextField[] arr = new TextField[tf.size()];
arr = tf.toArray(arr);
我正在编写一个 JavaFX 应用程序,我需要使用其 [=14] 添加 n 个 TextField
对象到 GridPane
中的一行=] 方法。 addRow
接受任意数量的参数,但它接收的 TextField
个对象的数量不是硬编码的。例如,
GridPane gp = new GridPane();
ArrayList<TextField> tf = new ArrayList<>();
for (int i = 0; i < user_entered_number; i++) {
tf.add(new TextField());
}
gp.addRow(row_index, /* all elements in tf*/);
我希望使用 allRow
方法将所有生成的 TextField
对象包含在 row_index
的 GridPane
行中。
如果这是可能的,我该怎么做?
GridPane.addRow(...)
method 采用 int
(行索引)和 Node
的可变参数。您可以为 varargs 参数传递一个数组,这样您就可以
gp.addRow(row_index, tf.toArray(new Node[0]));
或者,首先创建一个数组而不是列表:
GridPane gp = new GridPane();
TextField[] tf = new TextField[userEnteredNumber];
for (int i = 0; i < userEnteredNumber; i++) {
tf[i] = new TextField();
}
gp.addRow(row_index, tf);
我不确定我是否正确理解你的问题。是否要将 tf ArrayList 中的所有元素添加为 addRow() 方法中的参数?
addRow() 方法将可变参数作为参数。您是否尝试将 ArrayList 转换为数组,然后将其传递给方法?
TextField[] arr = new TextField[tf.size()];
arr = tf.toArray(arr);