Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting two JTables simultaneously

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.

like image 233
paulhudson Avatar asked Oct 21 '11 01:10

paulhudson


1 Answers

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

  • technically, sorting can be decided to be the responsibility of either the model or the view realm. There are (strongly debated in the past) pros and cons either way. Once done, stick to that decision everywhere in ui dev
  • keeping the index mapping between model and view coordinate system is where the challenges hides, either way
  • Swing/X decided to regard it a view responsibility, cramming any model-based custom sort/synch on top is fighting the system
like image 136
kleopatra Avatar answered Oct 12 '22 04:10

kleopatra