I have a choiceBox which represents a list objects. When the name representing one of those objects is changed by another bit of code the name in the drop down list for the
Just for completeness - in fx2 you are probably stuck with the replace approach as outlined in the other answer. Since fx8, there's a mechanism to tell the list to listen to changes of its contained items (precondition being, of course, that your item has properties and notifies listeners on change):
/** 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 items = FXCollections.observableList(
e -> new Observable[] {e.nameProperty()} );
items.addAll(...);
choiceBox = new ChoiceBox<>(items);
// tell the choice how to represent the item
StringConverter converter = new StringConverter() {
@Override
public String toString(Test album) {
return album != null ? album.getName() : null;
}
@Override
public Test fromString(String string) {
return null;
}
};
choiceBox.setConverter(converter);