JavaFX 2.0 Choice Box Issue. How to update a choiceBox, which represents a list of objects, when an object is updated?

后端 未结 3 467
独厮守ぢ
独厮守ぢ 2021-01-02 04:21

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

3条回答
  •  北海茫月
    2021-01-02 04:28

    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);
    

提交回复
热议问题