ObservableList:如何可靠地检测setAll?

时间:2014-11-18 12:55:16

标签: java javafx javafx-8 observablelist

在某些情况下,有必要检测 - 在ListChangeListener中,无需控制列表本身 - "所有数据换出",f.i。当我们需要清除像选择这样的状态时 - 在全新数据上,旧状态毫无意义。

可以获得全新的数据
  • list.setAll(...)
  • list.set(otherObservableList)如果list是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代码,f.i。在听ComboBox'项目:

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

存储旧的itemCount,并将其与当前的removedSize进行比较(我感到不舒服,旧状态经常因我的口味而过时),然而我很有可能用我的方法遗漏了一些东西。

问题是:

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

1 个答案:

答案 0 :(得分:4)

不幸的是,在监听器方面没有可靠的方法来检测它。

斗争始于默认实现,大多数情况如下:

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

如果您将空集合传递给setAll结果,并且触发的事件与您调用clear时完全相同。

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

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

相关问题