我有一个
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)
重现步骤:
addDataToLog
。addDataToLog
。事实证明,阅读 JavaDocs 会有很大帮助。只需将列表包装在
SortedList
中即可完成工作:
val sortedLogs = SortedList(logEntries)
tableViewMeasurementLog.items = sortedLogs
sortedLogs.comparatorProperty().bind(tableViewMeasurementLog.comparatorProperty())