gpt4 book ai didi

java - 如何通过 ListChangeListener 检索 ObservableList 中的更改项

转载 作者:塔克拉玛干 更新时间:2023-11-01 23:02:21 26 4
gpt4 key购买 nike

ListChangeListener.Change.wasUpdated() 用于检测 ObservableList 元素内的变化通过 ObservableList.observableArrayList(Callback<E,Observable[]> extractor) 创建.

如何检索导致触发更改的确切项目?

编辑

可能问题不够清楚,我举个例子。

class Foo {
private StringProperty name = new SimpleStringProperty();
public final StringProperty nameProperty() { return name; }
public final String getName() { return name.get(); }
public final void setName(String n) { name.set(n); }
public Foo(String fooName) { setName(fooName); }
}

// Creates an ObservableList with an extractor
ObservableList<Foo> fooList = FXCollections.observableArrayList(foo -> new Observable[] { foo.nameProperty() });
Foo fooA = new Foo("Hello");
Foo fooB = new Foo("Kitty");
fooList.add(fooA);
fooList.add(fooB);

fooList.addListener(new ListChangeListener<Foo>() {
public void onChanged(Change<Foo> c) {
while (c.next()) {
if (c.wasUpdated()) {
// One or more of the elements in list has/have an internal change, but I have no idea which element(s)!
}
}
}
});

fooB.setName("Mickey");

fooB.setName()将触发 ListChangeListener 中的更改,其中 wasUpdated()条件将返回 true .但是,我无法知道它是fooB。这在监听器中发生了变化。

这可能看起来微不足道,但我有一个 map 应用程序,其中的列表存储了 map 必须呈现的内容。当其中一项改变其位置(即纬度/经度)时,我需要在 map 上重新绘制。如果我不知道哪个项目改变了位置,我将不得不重新绘制我已有的所有内容。

最佳答案

您可以获得更改的项目的索引,这会为您提供一些有用的信息:

import javafx.beans.Observable;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener.Change;
import javafx.collections.ObservableList;

public class ListUpdateTest {

public static void main(String[] args) {

ObservableList<Foo> fooList = FXCollections.observableArrayList(foo -> new Observable[] { foo.nameProperty() });
Foo fooA = new Foo("Hello");
Foo fooB = new Foo("Kitty");
fooList.add(fooA);
fooList.add(fooB);

fooList.addListener((Change<? extends Foo> c) -> {
while (c.next()) {
if (c.wasUpdated()) {
int start = c.getFrom() ;
int end = c.getTo() ;
for (int i = start ; i < end ; i++) {
System.out.println("Element at position "+i+" was updated to: " +c.getList().get(i).getName() );
}
}
}
});

fooB.setName("Mickey");
}

public static class Foo {
private StringProperty name = new SimpleStringProperty();
public final StringProperty nameProperty() { return name; }
public final String getName() { return name.get(); }
public final void setName(String n) { name.set(n); }
public Foo(String fooName) { setName(fooName); }
}
}

请注意,您无法从列表更改事件中确定那些列表元素中发生更改的实际属性(因此,如果您的提取器指向两个或更多属性,则无法找到哪些属性发生了更改),并且没有办法获得以前的值(value)。不过,这对于您的用例来说可能已经足够了。

关于java - 如何通过 ListChangeListener 检索 ObservableList 中的更改项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47300969/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com