18

在某些情况下,有必要检测 - 在 ListChangeListener 中,无需控制列表本身 - “所有数据已换出”,即当我们需要清除某些状态(如选择)时 - 在全新数据上,旧状态毫无意义。

全新的数据可以通过

  • list.setAll(...)
  • list.set(otherObservableList) 如果列表是 ListProperty

考虑可以在 setAll 上触发哪种类型的更改(c 是更改,items 是观察到的列表,“subChangeCount”伪代码用于计算子更改):

// initially empty
assertEquals(0, items.size());
items.setAll(1, 2, 4);
assertEquals(1, c.subChangeCount());
assertTrue(c.wasAdded() && !c.wasReplaced());
assertEquals(0, c.getFrom());
assertEquals(c.getList().size(), c.getAddedSize()); 

// initially not empty
assertTrue(items.size() > 0);
items.setAll(1, 2, 4);
assertEquals(1, c.subChangeCount());
assertTrue(c.wasReplaced());
assertEquals(0, c.getFrom());
assertEquals(c.getList().size(), c.getAddedSize()); 

这似乎允许进行实用程序检查,例如:

boolean wasSetOrClearedAll(Change c) {
   if (c.getList().isEmpty()) return true;
   c.next();
   if (c.getAddedSize() == c.getList().size()) return true; 
   return false; 
}  

相比之下,内部 fx 代码, fi 在收听 ComboBox 的项目时:

while (c.next()) {
   comboBox.wasSetAllCalled = comboBox.previousItemCount == c.getRemovedSize();
   ... 
}
comboBox.previousItemCount = getItemCount();

存储旧的 itemCount 并将其与当前的 removedSize 进行比较(我对此感到不舒服,旧的状态对于我的口味来说太陈旧了),但是我很有可能在我的方法中遗漏了一些东西。

问题是:

在哪种情况下我的实用程序方法会失败(核心方法会正确检测到 setAll)?

4

1 回答 1

4

不幸的是,没有可靠的方法在侦听器端检测到这一点。

斗争从默认实现开始,它大多看起来像这样:

@Override
public boolean setAll(Collection<? extends E> col) {
    beginChange();
    try {
        clear();
        addAll(col);
    } finally {
        endChange();
    }
    return true;
}

如果您将一个空 Collection 传递给setAll结果,并且触发的事件都与您调用clear.

因此,您的方法也会在被调用时wasSetOrClearedAll返回(与核心实现一样)。trueclear

所以最后没有通用的检测setAll,这完全取决于你的用例。如果你可以缩小你试图检测的范围,你可以为此编写一个过滤器。

于 2014-12-09T09:53:54.707 回答