为了填充 JTable,我使用 AbstractTableModel。我还提供了使用 setAutoCreateRowSorter 进行排序的机会。所有这些操作都插入到计时器进程中,该进程在 1 分钟后执行数据刷新。如何在每次刷新数据时不改变排序?
谢谢
//... Type of **data** is a Matrix -> data[][]
//... Type of **columnName** is an Array -> columnName[]
//... Type of **table** is a JTable
//... Type of **model** is an AbstractTableModel
//...Other code Before
try {
table.setAutoCreateRowSorter(true);
} catch(Exception continuewithNoSort) { }
//...Other code After
Timer timerToRefresh = new Timer(0, new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
//Method that populates the matrix
popolateTable(nList);
} catch (Exception e1) {
e1.printStackTrace();
}
// Popolate the model
model = new DefaultTableModel(data,columnName){
private static final long serialVersionUID = 1L;
public boolean isCellEditable(int row, int column) {
return false;
}
};
// set the model to the table
table.setModel(model);
}
});
timerToRefresh.setDelay(60000); // Refresh every 60 seconds
timerToRefresh.start();
最佳答案
I take the new data to be included assigning the array data,
你不能这样做,因为这将创建一个新的 TableModel,它将重置排序器。
因此,假设您使用的是 DefaultTableModel,基本逻辑应该是:
model.setRowCount(0); // to delete the rows
for (each row of data in the Array)
model.addRow(...);
现在只有数据会被删除并添加到模型中,以便保留排序器。
另一个选项是在重新创建 TableModel 之前保存排序器的状态。您可以从 DefaultRowSorter 获取当前的排序键。所以基本逻辑是:
- getSortKeys()
- 刷新TableModel
- setSortKeys(...)
请参阅:Trying to get the sorter positon to retain after a table refresh 了解此方法的示例。
关于java - 如何在不更改 setAutoCreateRowSorter 完成的顺序的情况下刷新表(JTable)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36218593/