java - 如何在不更改 setAutoCreateRowSorter 完成的顺序的情况下刷新表(JTable)?

标签 java swing jtable tablerowsorter

为了填充 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 获取当前的排序键。所以基本逻辑是:

  1. getSortKeys()
  2. 刷新TableModel
  3. setSortKeys(...)

请参阅:Trying to get the sorter positon to retain after a table refresh 了解此方法的示例。

关于java - 如何在不更改 setAutoCreateRowSorter 完成的顺序的情况下刷新表(JTable)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36218593/

相关文章:

java - 在 WebView DialogFragment 中触摸时不显示软键盘

java - 将字符串转换为 am/pm 格式的日期和时间

java - JPanel 与 JTextField 或 JLabel 不更新

java - 在 JTable 中命名列

JTable 单元格更改上的 JAVA 更新数据库

Java 日期时间格式化程序 : DateTimeParseException with GMT-date

java - 日版字体错误

java - 问题子类化 JTextField : initial text value is not displayed

java - 将 JCombobox 渲染到正确的问题

java - JTable inside JLayeredPane inside JScrollPane - 你如何让它工作?