keeping the custom Sorting in jtable after table structure gets changed

1.3k Views Asked by At

I have a jtable where custom sorting is applied for data. When the table is launched initially , it has the columns with String data only so sorting goes fine. After table structure gets changed( new columns gets added which has a combination of Sting("N/A") and double data in same columns, the custom sorting algorithm seems to get removed. Now the columns with only string data still gets sorted because of defaultsorting with Jtable, but columns with mixed data gives classcastException. Is there I could keep the custom sorting or re-apply it as soon as tableStructureChange event occurs.

2

There are 2 best solutions below

1
Priyamal On
public void sortTable(){
    TableRowSorter<TableModel> sort = new TableRowSorter<TableModel>(Jtable.getModel());
   Jtable.setRowSorter(sort);

   List<RowSorter.SortKey> sortKeys = new ArrayList<>();
   sortKeys.add(new RowSorter.SortKey(4, SortOrder.ASCENDING));
   sortKeys.add(new RowSorter.SortKey(0, SortOrder.ASCENDING));
   sorter.setSortKeys(sortKeys);
    }

this is how you should actually sort a Jtable. try with this code and post if theres any exceptions

0
camickr On

The question is why is the tableStructureChanged event being generated? This implies the column structure of the table has changed, so how do you know the same columns will exist?

If you are doing a refresh of the table then why are you creating a whole new TableMode. Instead you can remove all the rows of data from the table (ie use setRowCount(0) in the DefaultTableModel) and then insert the new rows of data. This way the tableStructureEvent will not be generated.

The other option is to save the sorting information and recreate the sorter. You can get the current sort keys from the DefaultRowSorter. So the basic logic would be:

  1. getSortKeys()
  2. refresh TableModel
  3. recreate the sorter
  4. setSortKeys(...)

Check out: Trying to get the sorter positon to retain after a table refresh for a working example.