【问题标题】:Best practice to decorate an ObservableList and retain change events装饰 ObservableList 并保留更改事件的最佳实践
【发布时间】:2015-07-05 12:25:16
【问题描述】:

我的数据源提供了一个ObservableList<String>,但是对于我的ListView,我需要一个ObservableList<Warning>。

Warning 基本上只是字符串的装饰器,添加一个布尔值以提供一种方法来跟踪我的 ListView 中的复选框的状态,正如this 答案中所建议的那样。

class Warning {

    private final ReadOnlyStringWrapper name;
    private final BooleanProperty checked;

    /* ... */

}

目前我正在观察原始列表中的更改事件并手动添加/删除警告列表中的项目:

ObservableList<String> stringList = ...;
ObservableList<Warning> warningList = ...;

stringList.addListener(new ListChangeListener<String>() {

    @Override
    public void onChanged(ListChangeListener.Change<? extends String> change) {
        if (change.wasAdded()) {
            warningList.addAll(change.getAddedSubList().stream().map(Warning::new).collect(Collectors.toList()));
        } else if (change.wasRemoved()) {
            change.getRemoved().forEach(str -> {
                warningList.removeIf(w -> str.equals(w.name));
            });
        }
    }

});

我的问题是:有没有更优雅的方式来装饰我的字符串类型列表,这样它就可以用作警告类型列表而无需手动传递更改事件?

更准确地说:如果一个字符串被添加到原始列表中或从原始列表中删除,我希望立即在警告列表和 ListView 中看到此更改。

【问题讨论】:

  • EasyBind 框架对此有一些功能,基本上你可以调用ObservableList&lt;Warning&gt; warningList = EasyBind.map(stringList, Warning::new);。那里的实现使用TransformationList 的子类,所以我认为它基本上归结为你正在做的事情。
  • @James_D 谢谢。我不想仅仅针对这个问题包含一个完整的框架,但是TransformationList 仍然是一个很好的提示
  • 是的,有道理(尽管框架非常轻量级)。 source code 可用,您可以查看它是如何完成的。

标签: java design-patterns javafx


【解决方案1】:

自从你发布它以来,我一直在考虑这个问题。使用我在评论中建议的 EasyBind 将不起作用,因为每次您在映射列表上调用 get(...) 时,它都会创建一个新的 Warning。所以

stringList.add("foo");
warningList.get(0).setChecked(true);
assert warningList.get(0).isChecked();

会失败。

此外,如果源列表 (stringList) 中有重复条目,您的机制会出错(我认为),因为当从 @987654327 中删除单个元素时,您将从 warningList 中删除所有相应条目@。事实上,正确处理被移除的元素是相当棘手的。

这是一个基于 Tomas Mikula 的 MappedList 的解决方案,它缓存了源元素和映射元素之间的映射。它使用IdentityHashMap 来确保重复元素在两个列表中的行为正确。请注意,这仅适用于您希望在将项目添加到源列表时创建新对象的特定情况,因此它不打算(也不会起作用)作为 EasyBind 机制的替代品。

import java.util.ArrayList;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.function.Function;

import javafx.application.Application;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.ReadOnlyStringProperty;
import javafx.beans.property.ReadOnlyStringWrapper;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener.Change;
import javafx.collections.ObservableList;
import javafx.collections.transformation.TransformationList;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ListView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.CheckBoxListCell;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class WrappedObjectListExample extends Application {

    @Override
    public void start(Stage primaryStage) {
        ObservableList<String> stringList = FXCollections.observableArrayList("One", "Two", "Three");
        ObservableList<Warning> warningList = new CachingMappedList<Warning, String>(stringList, Warning::new);

        ListView<String> stringListView = new ListView<>(stringList);
        ListView<Warning> warningListView = new ListView<>(warningList);

        warningListView.setCellFactory(CheckBoxListCell.forListView(Warning::checkedProperty));

        TextField textField = new TextField();
        textField.setOnAction(e -> {
            if (! textField.getText().isEmpty()) {
                stringList.add(textField.getText());
                textField.setText("");
            }
        });

        Button remove = new Button("Remove");
        remove.setOnAction(e -> stringList.remove(stringListView.getSelectionModel().getSelectedIndex()));
        remove.disableProperty().bind(stringListView.getSelectionModel().selectedItemProperty().isNull());

        HBox lists = new HBox(10, stringListView, warningListView);
        VBox root = new VBox(10, lists, textField, remove);
        root.setPadding(new Insets(20));
        primaryStage.setScene(new Scene(root));
        primaryStage.show();
    }

    public static class Warning {
        private final ReadOnlyStringWrapper name = new ReadOnlyStringWrapper();
        private final BooleanProperty checked = new SimpleBooleanProperty();

        public Warning(String name) {
            this.name.set(name);
        }

        public final ReadOnlyStringProperty nameProperty() {
            return this.name.getReadOnlyProperty();
        }

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

        public final BooleanProperty checkedProperty() {
            return this.checked;
        }

        public final boolean isChecked() {
            return this.checkedProperty().get();
        }

        public final void setChecked(final boolean checked) {
            this.checkedProperty().set(checked);
        }

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

    }

    public static class CachingMappedList<S,T> extends TransformationList<S, T> {

        private final Function<T, S> mapper ;

        private final IdentityHashMap<T, S> cache ;

        public CachingMappedList(ObservableList<T> source, Function<T,S> mapper) {
            super(source);
            this.mapper = mapper ;
            this.cache = new IdentityHashMap<>();
        }

        @Override
        protected void sourceChanged(Change<? extends T> c) {

            fireChange(new Change<S>(this) {

                @Override
                public boolean wasAdded() {
                    return c.wasAdded();
                }

                @Override
                public boolean wasRemoved() {
                    return c.wasRemoved();
                }

                @Override
                public boolean wasReplaced() {
                    return c.wasReplaced();
                }

                @Override
                public boolean wasUpdated() {
                    return c.wasUpdated();
                }

                @Override
                public boolean wasPermutated() {
                    return c.wasPermutated();
                }


                @Override
                public boolean next() {
                    return c.next();
                }

                @Override
                public void reset() {
                    c.reset();
                }

                @Override
                public int getFrom() {
                    return c.getFrom();
                }

                @Override
                public int getTo() {
                    return c.getTo();
                }

                @Override
                public List<S> getRemoved() {
                    List<S> removed = new ArrayList<>();
                    c.getRemoved().forEach(t -> removed.add(cache.get(t)));
                    return removed;
                }

                @Override
                public int getPermutation(int i) {
                    return c.getPermutation(i);
                }

                @Override
                protected int[] getPermutation() {
                    throw new AssertionError("Unreachable code");
                }

            });

            // clean up cache:

            c.reset();
            while (c.next()) {
                if (c.wasRemoved()) {
                    c.getRemoved().forEach(cache::remove);
                }
            }            
        }

        @Override
        public int getSourceIndex(int index) {
            return index ;
        }

        @Override
        public S get(int index) {
            return cache.computeIfAbsent(getSource().get(index), mapper);
        }

        @Override
        public int size() {
            return getSource().size();
        }
    }

    public static void main(String[] args) {
        launch(args);
    }
}

【讨论】:

  • 哇,感谢您将时间投入到这个解决方案中!我认为缓存是重要的部分,因为我不希望每次访问列表中的任何项目时都进行动态映射,而是只在更改时创建/删除警告。我没有重复。但是由于我没有在我的问题中指定这一点,所以你指出了这一点。
  • 子类化TransformationList 似乎也正确,尽管它更冗长。它具有不可修改的优点,因此您可以强制执行关系(而不是仅仅依靠程序员不直接修改目标列表)。今天发布了一个相同的问题,所以看起来值得付出努力(我想纠正我说你可以使用 EasyBind.map(...) 作为解决方案的错误,这是完全错误的)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-26
  • 2020-08-15
  • 2011-03-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多