我有ObservableList和FilteredList,其中包含具有字段状态的附件。
FilteredList设置为ListView。我想将字段状态更改为State.REMOVED时,已更新FilteredList。

/* class Item */
private final ObservableList<Attached> attaches = FXCollections.observableArrayList();
private final FilteredList<Attached> filteredAttaches = attaches.filtered(attached -> attached.getState() != Attached.State.REMOVED);

/* Controller */
listAttached.setItems(item.getAttachesForDisplay());

/* class Attached */
public class Attached {

public static enum State {
    NEW, ATTACHED, REMOVED
}

private State state;
private final String path;
private final String name;

public Attached(State state, String path, String name) {
    this.state = state;
    this.path = path;
    this.name = name;
}

public State getState() {
    return state;
}

public void changeState(State state) {
    this.state = state;
    // Generate some event for update filtered list?
}

public String getPath() {
    return path;
}

public String getName() {
    return name;
}

@Override
public String toString() {
    return name;
}


}

最佳答案

使用JavaFX properties pattern创建模型类(Attached)。

public class Attached {

    public static enum State {
        NEW, ATTACHED, REMOVED
    }

    private final ObjectProperty<State> state = new SimpleObjectProperty<>();
    private final StringProperty path = new SimpleStringProperty();
    private final StringProperty name = new SimpleStringProperty();

    public Attached(State state, String path, String name) {
        setState(state);
        setPath(path);
        setName(name);
    }

    public ObjectProperty<State> stateProperty() {
        return state ;
    }

    public final State getState() {
        return stateProperty().get();
    }

    public final void setState(State state) {
       stateProperty().set(state);
    }

    public StringProperty pathProperty() {
        return path ;
    }

    public final String getPath() {
        return pathProperty.get();
    }

    public final void setPath(String path) {
        pathProperty().set(path);
    }

    public StringProperty nameProperty() {
        return name ;
    }

    public final String getName() {
        return nameProperty().get();
    }

    public final void setName(String name) {
        nameProperty().set(name);
    }

    @Override
    public String toString() {
        return getName();
    }

}


现在使用extractor创建基础列表,以便在stateProperty更改时触发更新事件:

private final ObservableList<Attached> attaches =
    FXCollections.observableArrayList(attached -> new Observable[]{attached.stateProperty()});
private final FilteredList<Attached> filteredAttaches =
    attaches.filtered(attached -> attached.getState() != Attached.State.REMOVED);

09-27 09:40