I have two JTables built with different objects of same TableModel class. When I click on one column in Table 1 to sort, the requirement is that the other Table 2 should also get sorted based on the same column that was clicked on in JTable 1. Is there any way to find what column in Table 1 was used or the sorting was based on. Using that, is there any way to invoke sorting via any method call on Table 2 for the same column.
Please provide your suggestions or pointers to any java apis. Also, if there is any link having an example would be of great help. -Paul.
The way to go is to listen to the changes of the table's sorter and set the sortKeys of the second table to the same:
RowSorterListener l = new RowSorterListener() {
@Override
public void sorterChanged(RowSorterEvent e) {
if (RowSorterEvent.Type.SORT_ORDER_CHANGED == e.getType()) {
RowSorter sorter = e.getSource();
otherTable.getRowSorter().setSortKeys(sorter.getSortKeys());
}
}
};
table.getRowSorter().addRowSorterListener(l);
If you need to keep the synch both ways, register the listener to both and add some logic to do nothing when the sort change was triggered by the listener.
Edit
after writing a nearly same comment twice (to the answers of suggesting doing the sorting on the model), decided to add it here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With