How can I resort (RowSort) after an insert in JTable?

1.1k views Asked by At

I would like to know: How can I reorder (re-sort) a JTable rows after I insert a row?

I use the next code:

TableModel model = new DefaultTableModel(rows, columns) {
  public Class getColumnClass(int column) {
    Class returnValue;
    if ((column >= 0) && (column < getColumnCount())) {
      returnValue = getValueAt(0, column).getClass();
    } else {
      returnValue = Object.class;
    }
    return returnValue;
  }
};
JTable table = new JTable(model);
RowSorter<TableModel> sorter = new TableRowSorter<TableModel>(model);
table.setRowSorter(sorter);
JScrollPane pane = new JScrollPane(table);

This code works fine, and I can add new rows without problem, but I want after I insert a new row it re-sorts again using the first column ASC...

1

There are 1 answers

0
MadProgrammer On

If you want real time updates, then you could try calling TableRowSorter#setSortsOnUpdates on the TabkeRowSorter and pass it true...

Otherwise, if you want to control when updates are sorted, you could just call TableRowSorter#sort

If you want to modify the sort order programically, then take a look at Sorting and Filtering which has an example