Java:如何将动态数量的参数传递给方法

时间:2017-05-22 22:32:47

标签: java javafx methods variadic-functions

我正在编写一个JavaFX应用程序,我需要使用redirect('/home');方法将 n 数量的const config = { type: 'POST', url: 'test.asp', success: function () {} } if (testObj != undefined) config.data = testObj $.ajax(config) 个对象添加到TextField的行中。 GridPane接受任意数量的参数,但它接收的addRow个对象的数量不是硬编码的。例如,

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*/); 行的TextField行中包含所有生成的GridPane个对象。

如果有可能,我该怎么办?

2 个答案:

答案 0 :(得分:2)

GridPane.addRow(...) method需要int(行索引)和Node s的变量。您可以为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);

答案 1 :(得分:0)

我不确定我是否理解你的问题。是否要将来自tf ArrayList的所有元素添加为addRow()方法中的参数?

addRow()mathod将varargs作为参数。您是否尝试将ArrayList转换为数组,然后将其传递给方法?

TextField[] arr = new TextField[tf.size()];
arr = tf.toArray(arr);