如何在不更改使用 setAutoCreateRowSorter 完成的排序的情况下刷新 table (JTable)?
How to refresh a table (JTable) without changing the ordering done with setAutoCreateRowSorter?
为了填充 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(...)
有关此方法的示例,请参阅:。
为了填充 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(...)
有关此方法的示例,请参阅: