将项目添加到用户按特定列排序的 TableView,同时尊重排序

问题描述 投票:0回答:1

我有一个

TableView
,用户可以按其任何列进行排序。根据应用程序中的其他事件,我想将数据添加到
TableView
。但是,当我添加数据时,新行始终出现在
TableView
的底部,即使它应该根据排序顺序出现在其他位置。

因此,我的问题是,如何将数据添加到

TableView
,以便
TableView
仍然根据用户选择的列正确排序。

这是控制

TableView
的相关代码:

@FXML
private lateinit var tableColumnMeasurementLogBib: TableColumn<LogEntry, Int>

@FXML
private lateinit var tableColumnMeasurementLogResult: TableColumn<LogEntry, Double>

@FXML
private lateinit var tableColumnMeasurementLogTimestamp: TableColumn<LogEntry, LocalDateTime>

@FXML
private lateinit var tableViewMeasurementLog: TableView<LogEntry>

private val logEntries = FXCollections.observableArrayList<LogEntry>()

private fun setupMeasurementLog() {
    tableViewMeasurementLog.items = logEntries
    
    tableColumnMeasurementLogTimestamp.cellValueFactory = PropertyValueFactory(LogEntry::timestamp.name)
    tableColumnMeasurementLogResult.cellValueFactory = PropertyValueFactory(LogEntry::result.name)
    tableColumnMeasurementLogBib.cellValueFactory = PropertyValueFactory(LogEntry::athleteId.name)

    tableColumnMeasurementLogTimestamp.setCellFactory {
        object : TableCell<LogEntry, LocalDateTime>() {
            override fun updateItem(item: LocalDateTime?, empty: Boolean) {
                super.updateItem(item, empty)
                if (empty || item == null) {
                    text = ""
                    return
                }

                text = measurementLogDateTimeFormatter.format(item)
            }
        }
    }
}

private fun addDataToLog(athleteId: Int, result: Double, timestamp: LocalDateTime) {
    logEntries.add(LogEntry(athleteId, result, timestamp))
}

data class LogEntry(val athleteId: Int, val result: Double, val timestamp: LocalDateTime)

重现步骤:

  1. 使用一些值调用
    addDataToLog
  2. 在 UI 中,单击任意列标题即可按该列对表格进行排序。
  3. 再次致电
    addDataToLog
  4. 新数据行将始终出现在底部,无论它实际应该出现在哪里(根据排序列)。
java kotlin javafx tableview
1个回答
0
投票

事实证明,阅读 JavaDocs 会有很大帮助。只需将列表包装在

SortedList
中即可完成工作:

val sortedLogs = SortedList(logEntries)
tableViewMeasurementLog.items = sortedLogs
sortedLogs.comparatorProperty().bind(tableViewMeasurementLog.comparatorProperty())
© www.soinside.com 2019 - 2024. All rights reserved.