简体   繁体   中英

How to refresh a table (JTable) without changing the ordering done with setAutoCreateRowSorter?

To populate a JTable, I'm using AbstractTableModel. I have also included the opportunity to make a sort using setAutoCreateRowSorter. All these operations are inserted inside a timer process, which after 1 Minute performs a data refresh. How can I not change the sort every time the data is refreshed?

Thank you

//... 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,

Well you cant do that because that will create a new TableModel which will reset the sorter.

So, assuming you are using the DefaultTableModel, the basic logic should be:

model.setRowCount(0); // to delete the rows

for (each row of data in the Array)
    model.addRow(...);

Now only the data will be removed and added to the model so the sorter will remain.

The other option is to save the state of the sorter before recreating the TableModel. You can get the current sort keys from the DefaultRowSorter. So the basic logic would be:

  1. getSortKeys()
  2. refresh TableModel
  3. setSortKeys(...)

See: Trying to get the sorter positon to retain after a table refresh for an example of this approach.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM