jshapy8 jshapy8 - 1 year ago 87
Java Question

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.
addRow
accepts any number of arguments, but the amount of of
TextField
objects it receives is not hard coded. 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.

If this is even possible, how can I do it?

Answer Source

The GridPane.addRow(...) method takes an int (the row index) and a varargs of Nodes. You can pass an array for a varargs parameter, so you can do

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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download