I create several components dynamically:

for (int i = 0; i <= 2; i++) { Switch sw = new Switch(); StringProperty str = new SimpleStringProperty(String.valueOf(shop.bag[i].get())); Text text1 = new Text(); text1.textProperty().bind(str); final int finalI = i; sw.action = () - > { ind[0] = finalI * 3 + sw.index; str[ind[0]].set(String.valueOf(shop.bag[finalI * 3 + sw.index].get())); }; } 

The code above works fine, but initially the text is not updated, the update occurs only after calling the sw.setOnMouseClicked() method. If the StringProperty str taken out of the loop and made as a field, then all components will have the same text. How can this problem be solved?

    1 answer 1

    You try the code

     ind[0] = finalI * 3 + sw.index; str[ind[0]].set(String.valueOf(shop.bag[finalI * 3 + sw.index].get())); 

    put out sw.action . Or check that you have in shop.bag[i].get() at the time of initialization.

    You do not assign a value during initialization.

    Update

    Save the elements created dynamically in the ArrayList and then initialize the values ​​of their properties for each element after loading the data in shop.bag. So you also have a reference index.

    • It turns out that during the initialization of the components shop.bag is still empty, I do not know how to update it. If you link directly, then the text is the same for all components - Evgeny
    • text1.textProperty (). bind (shop.bag [finalI * 3 + sw.index] .asString ()); - Evgeny
    • The components of the Switch type that are created in the loop, when clicked, change the index (the index property), and when the StringProperty str property is inside this loop, everything works. When I take str out of a loop, make it an array of properties, there is no response to changes in the index. - Evgeny