[英]Binding two ObservableLists of different Objects. (Without EasyBind)
ObservableList<String> src = FXCollections.observableArrayList();
ObservableList<Integer> other = FXCollections.observableArrayList();
//Create binding.
src.addAll("1", "2", "3");
System.out.println(other);//Should print [1, 2, 3].
Above I have an idea of what I am trying to do.以上我对我正在尝试做的事情有一个想法。
As items are added and removed to the src list, the other list is synchronized along with it.在 src 列表中添加和删除项目时,另一个列表也随之同步。 Every item in the src list has an equivalent to the items in the other list. src 列表中的每个项目都与另一个列表中的项目等效。 The other list contains "translated" values from the src list, of course.当然,另一个列表包含来自 src 列表的“翻译”值。
Many have recommended using EasyBind, but I would like to understand how to do this manually first.许多人建议使用 EasyBind,但我想先了解如何手动执行此操作。
You could use a listener for this like in this example:您可以在此示例中使用侦听器:
ObservableList<String> src = FXCollections.observableArrayList();
ObservableList<Integer> other = FXCollections.observableArrayList();
// Create binding.
src.addListener(new ListChangeListener<String>() {
@Override
public void onChanged(ListChangeListener.Change<? extends String> change) {
while (change.next()) {
for (String changedString : change.getList()) {
other.add(Integer.valueOf(changedString));
}
}
}
});
src.addAll("1", "2", "3");
System.out.println(other); // Prints out [1, 2, 3].
Or you can make a method for adding to List, like:或者您可以创建一个添加到 List 的方法,例如:
private void addToList(String s) {
src.add(s);
other.add(Integer.valueOf(s));
}
Happy Coding,快乐编码,
Kalasch卡拉什
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.