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<Test> items = FXCollections.observableList(
e -> new Observable[] {e.nameProperty()} );
items.addAll(...);
choiceBox = new ChoiceBox<>(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;
}
};
choiceBox.setConverter(converter);
I had the same issue in JavaFX 8 (with ComboBox too). I was able to get the same functionality by removing the item then adding a new one at the same location.
Example:
This gets selected item, creates a new item, then calls the replace method:
Channel selected = channelChoiceBox.getSelectionModel().getSelectedItem();
Channel newChan = new Channel("Example", "Channel");
replaceChannel(newChan, selected);
This replaces the selected channel with the new one, effectively editing it:
private void replaceChannel(Channel newChan, Channel oldChan) {
int i = channelChoiceBox.getItems().indexOf(oldChan);
channelChoiceBox.getItems().remove(oldChan);
channelChoiceBox.getItems().add(i, newChan);
channelChoiceBox.setValue(newChan);
}
It's not ideal, but does the job.
Disclaimer: I'm new to Java and programming in general.
Yes. This seems to be issue with JavaFx. I too had faced that. Use ComboBox instead of ChoiceBox that will work.