Java将Map大小与ObjectProperty绑定< Integer>

brccelvz  于 2023-03-11  发布在  Java
关注(0)|答案(1)|浏览(108)

我有一个UI元素,需要在Map更新时更新。我想将Map大小与ObjectProperty绑定,但.bind()方法不允许。如何将属性与Map大小绑定?代码示例:

public class ContainerOJ {

    protected final ObjectProperty<Integer> objCount;
    protected Map<String, String> stackMap;

    public ContainerOJ() {
        this.objCount = new SimpleObjectProperty<>(0);
        this.stackMap = new HashMap<>();

//        objCount.bind(stackMap.size());
    }

    public void addToStack(String newObj) {
        if (stackMap.get(newObj) != null) {
            /* Obj:{}, already exists in the Stack:{} */
            return;
        }

        stackMap.put(newObj, newObj);
        objCount.set(stackMap.size());
    }

    public Integer getObjCount() {
        return objCount.get();
    }

    public ObjectProperty<Integer> objCountProperty() {
        return objCount;
    }
}
cgh8pdjw

cgh8pdjw1#

不应使用ObjectProperty<Integer>。请改用ReadOnlyIntegerWrapperReadOnlyIntegerProperty

protected final ReadOnlyIntegerWrapper objCount;

public ContainerOJ() {
    this.objCount = new ReadOnlyIntegerWrapper();
    this.stackMap = new HashMap<>();
}

//...

public int getObjCount() {
    return objCount.get();
}

public ReadOnlyIntegerProperty objCountProperty() {
    return objCount.getReadOnlyProperty();
}

实际上,您可以使用ObservableMap来简化此操作:

protected final ReadOnlyIntegerWrapper objCount;
protected final ObservableMap<String, String> stackMap;

public ContainerOJ() {
    this.objCount = new ReadOnlyIntegerWrapper();
    this.stackMap = FXCollections.observableHashMap();

    objCount.bind(Bindings.size(stackMap));
}

public void addToStack(String newObj) {
    stackMap.putIfAbsent(newObj, newObj);
}

public int getObjCount() {
    return objCount.get();
}

public ReadOnlyIntegerProperty objCountProperty() {
    return objCount.getReadOnlyProperty();
}

我不知道为什么你要在这里使用Map,因为你的键和值是一样的,看起来你应该使用Set,更具体地说,ObservableSet:

protected final ReadOnlyIntegerWrapper objCount;
protected final ObservableSet<String> stackMap;

public ContainerOJ() {
    this.objCount = new ReadOnlyIntegerWrapper();
    this.stackMap = FXCollections.observableSet();

    objCount.bind(Bindings.size(stackMap));
}

public void addToStack(String newObj) {
    stackMap.add(newObj);
}

public int getObjCount() {
    return objCount.get();
}

public ReadOnlyIntegerProperty objCountProperty() {
    return objCount.getReadOnlyProperty();
}

相关问题