如何像更新 ForEach 一样绑定列表?
How to bind lists like an updating 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 的可能性。
third-party 库 ReactFX 有这方面的功能。你可以做到
ObservableList<Point> points = FXCollections.observableArrayList();
ObservableList<PointRepresentation> representations = LiveList.map(points, PointRepresentation::new);
这将在 add/remove 等更改为 points
时自动更新 representations
。
这是一个示例代码:
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 的可能性。
third-party 库 ReactFX 有这方面的功能。你可以做到
ObservableList<Point> points = FXCollections.observableArrayList();
ObservableList<PointRepresentation> representations = LiveList.map(points, PointRepresentation::new);
这将在 add/remove 等更改为 points
时自动更新 representations
。