JavaFX 2.0 selection box problem How do I update the choicebox representing the object list when updating objects?
I have a list object choice@R_680_2419 @. when the name representing one of the objects is changed by another code, the name in the drop-down list of the selection box will not change For example, if I have a selection box consisting of a list of test objects The test code is as follows:
class Test {
String name;
public Test(String name) {
this.name = name;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
@Override
public String toString() {
return name;
}
}
Then select @ R_ 680_ 2419 @ as follows:
Choice@R_680_2419@<Test> chi = new Choice@R_680_2419@<>();
ObservableList<Test> items = FXCollections.observableArrayList();
chi.setItems(items);
items.addAll(new Test("ITEM1"),new Test("ITEM2"),new Test("ITEM3"));
Choice@R_680_2419 @The Item1, Item2, and Item3 lists are displayed
If I then change the name of one of the projects through the following code:
items.get(1).setName("CHANGED");
Choice@R_680_2419 @The Item1, Item2 and Item3 lists will still be displayed How can I make it update and display lists Item1, changed and Item3?
Solution
Just for completeness – in FX2, you may be trapped by the replace approach outlined in another answer Starting with fx8, there is a mechanism to tell a list to listen for changes to its contained items (of course, if your item has properties and notifies the listener of changes):
/** changed item to
* - use property and notify on change
* - not override toString (for visuals,use converter instead)
*/
class Test {
StringProperty name;
public Test(String name) {
setName(name);
}
public StringProperty nameproperty() {
if (name == null) name = new SimpleStringProperty(this,"name");
return name;
}
public void setName(String name) {
nameproperty().set(name);
}
public String getName() {
return nameproperty().get();
}
}
// use in collection with extractor
ObservableList<Test> items = FXCollections.observableList(
e -> new Observable[] {e.nameproperty()} );
items.addAll(...);
choice@R_680_2419@ = new Choice@R_680_2419@<>(items);
// tell the choice how to represent the item
StringConverter<Test> converter = new StringConverter<Test>() {
@Override
public String toString(Test album) {
return album != null ? album.getName() : null;
}
@Override
public Test fromString(String string) {
return null;
}
};
choice@R_680_2419@.setConverter(converter);
