簡體   English   中英

如何在不更改setAutoCreateRowSorter的順序的情況下刷新表(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();

我將分配數組數據包含在新數據中,

好吧,您不能這樣做,因為這將創建一個新的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(...)

有關此方法的示例,請參見: 嘗試使表刷新后保留排序器位置

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM