JavaFx - 将MapProperty键绑定到SetProperty

时间:2016-03-31 15:52:06

标签: java javafx

我有两个属性:

[DllImport("Dll\vulkan-1.dll", EntryPoint = "VkGetPhysicalDeviceMemoryProperties")]
public extern static void GetPhysicalDeviceMemoryProperties(
     PhysicalDevice physicalDevice,
     PhysicalDeviceMemoryProperties* pMemoryProperties);   <-error here

SetProperty<String> set

我的问题是如何将此map属性的键集绑定到set属性?

2 个答案:

答案 0 :(得分:2)

您可以自己创建一个SetBinding课程来收听ObservableMap中的更改:

public class MapKeyBinding<K> extends SetBinding<K> {

    private final ObservableSet<K> readonlyView;

    public <V> MapKeyBinding(ObservableMap<K, V> map) {
        ObservableSet<K> set = FXCollections.observableSet();
        set.addAll(map.keySet());
        readonlyView = FXCollections.unmodifiableObservableSet(set);
        map.addListener((MapChangeListener.Change<? extends K, ? extends V> change) -> {
            if (change.wasAdded() != change.wasRemoved()) {
                if (change.wasRemoved()) {
                    set.remove(change.getKey());
                } else {
                    set.add(change.getKey());
                }
            }
        });
    }

    @Override
    protected ObservableSet<K> computeValue() {
        return readonlyView;
    }

}

使用

ReadOnlySetProperty<String> set = new ReadOnlySetWrapper(new MapKeyBinding(map)).getReadOnlyProperty();

请注意,此处不使用SetProperty,因为您可以使用ObservableSet

ObservableSet<String> set = new MapKeyBinding(map);

但是,如果您每次修改ObservableSet时仍坚持替换Map,则可以使用绑定API:

 set.bind(Bindings.createObjectBinding(() -> new MapKeyBinding<>(map.get()), map));

答案 1 :(得分:0)

您可能应该将其公开为ReadOnlySetProperty而不是完整的SetProperty,因为Map的keySet无法替换:

ReadOnlySetProperty<String> set = new ReadOnlySetWrapper(
    FXCollections.observableSet(map.keySet())).getReadOnlyProperty();