如何像更新ForEach一样绑定列表



下面是一个示例代码:

public class Example3 {
class Point {
int x, y; // these can be properties if it matters
}
class PointRepresentation {
Point point; // this can be a property if it matters
public PointRepresentation(Point point) {
this.point = point;
}
}
Example3() {
ObservableList<Point> points = FXCollections.observableArrayList();
ObservableList<PointRepresentation> representations = FXCollections.observableArrayList();
points.forEach(point -> representations.add(new PointRepresentation(point)));
}
}

我有一个数据保持器Point和一个数据表示器PointRepresentation。我有一个点的列表,我希望列表中的每个点在第二个列表中都有一个等价的表示对象。我给出的代码适用于初始化,但如果以后有任何更改,上面的代码将不会更新。

我现在所做的是使用更改侦听器来同步列表(根据更改对象添加和删除元素),这还可以,但我想知道是否有更简单的解决方案。我在寻找类似于"for each bind"的东西,这意味着:对于一个列表中的每个元素,另一个中都有一个元素,它们之间有指定的关系[在我的情况下是那个构造函数]。在伪代码中:

representations.bindForEach(points, point -> new PointRepresentation(point));

我看了一些东西:列表的提取器,但当它们所持有的对象中的属性发生变化时,而不是当列表本身发生变化时发送更新。因此,在我的情况下,如果点中的x发生变化,我可以制作一个提取器来通知它http://docs.oracle.com/javase/8/javafx/api/javafx/beans/binding/ListBinding.html,所以也许自定义绑定可以做到,但我不知道它是否更简单。

对于数组而不是列表,是否也有类似的解决方案?我看到了http://docs.oracle.com/javase/8/javafx/api/javafx/collections/ObservableArray.html作为一种可能性。

第三方库ReactFX具有此功能。你可以做

ObservableList<Point> points = FXCollections.observableArrayList();
ObservableList<PointRepresentation> representations = LiveList.map(points, PointRepresentation::new);

这将在对points进行添加/删除等更改时自动更新representations

最新更新