1

Basically, I would like to make a loop which would change the name of every TextField to a name stored in a folder. I fully understand how to make loops for int values, but completely don't know how to make it to affect a methods (like I show it below). Any ideas how to solve the problem?

Check the code and I am sure you will understand what I mean

@FXML
private TextField t1;

@FXML
private TextField t2;

// etc...

@FXML
void music(ActionEvent event) {

    if (event.getSource() == dmusic) {
        File folder = new File("C:\\eclipse\\MP2");
        File[] list = folder.listFiles();

        for (int i = 0; i < list.length; i++) {

            System.out.println(list[i].getName());

            // Here i would like to update TextField name for every "t" method like I did below, but without writing it all the time.

        }

        //      t1.setText(list[0].getName());  // can't make infinite "t"'s and would like to make it in a loop
        //      t2.setText(list[1].getName());
        //      t3.setText(list[2].getName());
        //      t4.setText(list[3].getName());
        //      t5.setText(list[4].getName());
        //      t6.setText(list[5].getName());
        // ...
    }
}
0

1 Answer 1

1

Try using an arraylist

Arraylist<TextField> fields = new ArrayList<>();
<add TextFields to arraylist>

and then use

for(TextField field : fields) {
    field.setText("");
}

or

for(int i=0; i< fields.size(); i++){
    fields.get(i).setText("");
}

to access your individual text fields.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you, i will try :)
Why an ArrayList? Arrays.asList(...); This is more convenient than n calls to add. Alternatively an array could be used: TextField[] fields = new TextField[]{ ... };
I do not have a reason for choosing ArrayList over an array in this instance. Either would work.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.