JavaFX:修改基础列表时更改过滤列表谓词

JavaFX: Changing filtered list predicate when the underlying list is modified

我有一个用 Kotlin 编写的 JavaFX 应用程序。该应用程序显示了所有具有日期的账单列表:

data class Bill(
    val date: LocalDate
    // ...
)

账单存储在一个可观察列表中,由过滤列表包装。

我希望用户能够设置过滤帐单的日期范围。除此之外,我希望该范围在修改基础账单列表时自动更改。该日期范围的下限和上限保存为属性。

我已经尝试过两种方法:

这是一个简单的例子:

import javafx.application.Application
import javafx.beans.binding.Bindings
import javafx.beans.binding.ObjectBinding
import javafx.beans.property.SimpleObjectProperty
import javafx.collections.FXCollections
import javafx.collections.ObservableList
import javafx.collections.transformation.FilteredList
import javafx.stage.Stage
import java.time.LocalDate
import java.util.function.Predicate

data class Bill(
    val date: LocalDate
)

class Example : Application() {
    private val bills: ObservableList<Bill> = FXCollections.observableArrayList()
    private val filteredBills: FilteredList<Bill> = FilteredList(bills)

    val latestBillDateBinding: ObjectBinding<LocalDate?> =
        Bindings.createObjectBinding({
            bills.maxOfOrNull { it.date }
        }, bills)

    // In the original code, the UI is bidirectionally bound to this
    val endingDateProperty = SimpleObjectProperty(LocalDate.now())
    var endingDate: LocalDate?
        get() = endingDateProperty.value
        set(value) {
            endingDateProperty.value = value
        }

    init {
        latestBillDateBinding.addListener { _, oldValue, newValue ->
            if (endingDate == oldValue)
                endingDate = newValue
        }

        // First approach - does not refilter
        filteredBills.predicate = Predicate {
            it.date == endingDate
        }

        // Second approach - throws exceptions
        /*
        filteredBills.predicateProperty().bind(Bindings.createObjectBinding({
            // This is just an example.
            // The actual predicate checks whether the date is in a valid range.
            Predicate { it.date == endingDate }
        }, endingDateProperty))
        */

        bills += Bill(LocalDate.now())
    }

    fun alterData() {
        println("Altering data")
        bills += Bill(bills.last().date.plusDays(1))
    }

    fun accessData() {
        println("Accessing data")
        println(filteredBills)
    }

    fun changeEndingDate() {
        println("Changing filter")
        endingDate = endingDate?.plusDays(1)
    }

    override fun start(primaryStage: Stage) {
        accessData()
        alterData()
        accessData()
        changeEndingDate()
        accessData()
    }
}

第一种方法的输出:

Accessing data
[Bill(date=2021-07-20)]
Altering data
Accessing data
[Bill(date=2021-07-20), Bill(date=2021-07-21)]
Changing filter
Accessing data
[Bill(date=2021-07-20), Bill(date=2021-07-21)]

第二种方法的输出:

Accessing data
[Bill(date=2021-07-20)]
Altering data
Accessing data
Exception in Application start method
Exception in thread "main" java.lang.reflect.InvocationTargetException
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at java.base/sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:1051)
Caused by: java.lang.RuntimeException: Exception in Application start method
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:900)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication(LauncherImpl.java:195)
    at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: java.util.NoSuchElementException
    at java.base/java.util.AbstractList$Itr.next(AbstractList.java:377)
    at java.base/java.util.AbstractCollection.toString(AbstractCollection.java:472)
    at java.base/java.lang.String.valueOf(String.java:2951)
    at java.base/java.io.PrintStream.println(PrintStream.java:897)
    at org.example.App.accessData(App.kt:63)
    at org.example.App.start(App.kt:74)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication1(LauncherImpl.java:846)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runAndWait(PlatformImpl.java:474)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater(PlatformImpl.java:447)
    at java.base/java.security.AccessController.doPrivileged(Native Method)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater(PlatformImpl.java:446)
    at javafx.graphics/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
    at javafx.graphics/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at javafx.graphics/com.sun.glass.ui.win.WinApplication.lambda$runLoop(WinApplication.java:174)
    ... 1 more

如果存在重新筛选列表的方法,我更喜欢第一种方法。我还想知道是什么导致了我在使用第二种方法时遇到的问题,以及我该如何解决它。

注意:也欢迎使用 Java 编写的代码示例。

正如 kleopatra 指出的那样,过滤列表及其谓词​​内容的更新顺序似乎有问题。

不是向 latestBillDateBinding 添加监听器,它应该根据源列表更改谓词,而是可以将类似的监听器添加到源列表本身:

bills.addListener(object : ListChangeListener<Bill> {

    var latestBillDate: LocalDate? = null

    override fun onChanged(c: ListChangeListener.Change<out Bill>) {
        val newMax = bills.maxOfOrNull { it.date }

        if (endingDate == latestBillDate){
            endingDate = newMax
        }

        latestBillDate = newMax
    }
})

这里的区别是最新账单日期不再通过绑定计算,而是存储为常规变量并在新的监听器中计算。

我认为之所以可行,是因为在 过滤列表收到更改事件后 调用了源列表中的侦听器,使其能够在谓词终于改变了。