javaswingjtabletablemodeltablerowsorter

Get sorted TableModel


I am trying to get the sorted TableModel of a JTable which is done by the following simple regex criteria:

try {
    TableRowSorter<TableModel> sortRow = new TableRowSorter<>(testTable.getModel());
    testTable.setRowSorter(sortRow);
    String sortString = "Something";
    sortRow.setRowFilter(RowFilter.regexFilter("(?i)" + sortString));
}

which will sort the data according to sortString.

But when I try to do the following :

try {
    TableRowSorter<TableModel> sortRow = new TableRowSorter<>(testTable.getModel());
    // ....
    // previous code
    // ....
    TableModel tM = testTable.getModel();
    someOtherTestTable.setModel(tM); //<---Here
}

It provides me the DefaultTableModel. So, my question is this: How do I get the sorted TableModel so that I can post to another JTable?


Solution

  • A TableRowSorter conditions the view, JTable; the model, TableModel, remains unchanged. If the underlying model of the RowSorter remains the same, you should be able apply the old TableRowSorter to the new JTable using setRowSorter().

    …
    someOtherTestTable.setModel(tM);
    someOtherTestTable.setRowSorter(sortRow);