[英]Java: How to pass a dynamic amount of arguments to a method
I am writing a JavaFX app and I need to add n amount of TextField
objects to a row in a GridPane
using its addRow
method. 我写一个JavaFX应用程序,我需要的施氮量添加
TextField
在对象的行GridPane
使用其addRow
方法。 addRow
accepts any number of arguments, but the amount of of TextField
objects it receives is not hard coded. addRow
可以接受任意数量的参数,但是接收到的TextField
对象的数量不是硬编码的。 For example, 例如,
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*/);
I wish to include all generated TextField
objects in the GridPane
row at row_index
using the allRow
method. 我希望使用
allRow
方法将所有生成的TextField
对象包括在GridPane
行的row_index
allRow
。
If this is even possible, how can I do it? 如果有可能,我该怎么办?
The GridPane.addRow(...)
method takes an int
(the row index) and a varargs of Node
s. GridPane.addRow(...)
方法采用int
(行索引)和Node
的GridPane.addRow(...)
。 You can pass an array for a varargs parameter, so you can do 您可以为varargs参数传递数组,因此您可以
gp.addRow(row_index, tf.toArray(new Node[0]));
Alternatively, just create an array instead of a list in the first place: 或者,只需首先创建一个数组而不是一个列表:
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);
I am not sure if I understand your problem properly. 我不确定我是否正确理解您的问题。 Do you want to add all the elements from tf ArrayList as arguments in addRow() method?
是否要将tf ArrayList中的所有元素添加为addRow()方法中的参数?
addRow() mathod takes varargs as an argument. addRow()mathod使用varargs作为参数。 Did you try convert the ArrayList into array and then pass it to the method?
您是否尝试将ArrayList转换为array,然后将其传递给方法?
TextField[] arr = new TextField[tf.size()];
arr = tf.toArray(arr);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.