Sort two JTables at the same time

I have two JTables built with different objects of the same TableModel class. When I click on one column in table 1 for sorting, the requirement is that another table 2 also needs to be sorted based on the same column that JTable 1 was clicked on. Is there a way to find which column in table 1 was used or sorting was based. Using this, is there a way to invoke sorting using any method call in table 2 for the same column.

Please submit your suggestions or pointers to any java page. In addition, if there is any link with an example, it will be very useful. -Paul.

+6
source share
3 answers

The way to listen is to listen to the table sorter changes and set the sortKeys of the second table to the same thing:

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 synchronization in both directions, register a listener for both and add some logic to do nothing when the sort change was called by the listener.

Edit

after writing almost the same comment twice (to the answers to the proposal to sort by model), I decided to add it here

  • technically, sorting can be solved as a responsibility, as well as a model or field of view. In the past (mostly discussed) the pros and cons. After that, stick to this solution everywhere in ui dev
  • maintaining the index mapping between the model and the view coordinate system is where problems are hidden, anyway
  • Swing / X decided to consider this as the responsibility for browsing, clogging any custom type / synchronization based on the model actually fights the system.
+8
source

I think the user interface only complicates the problem. Think about it in terms of the basic data of the table, and you will feel better. If you can get it right, it's just a matter of display.

Sorting a collection of values ​​is easy. You can use java.util.Collections and Comparable for this.

The trick is maintaining a relationship between the indices of the sorted column and the rest of the columns in the row.

+1
source

The easiest way is to sort the underlying data. Or you can implement a sorter and add it to both tables.

The following thread shows how to implement it in JXTable:

http://www.java.net/node/680987

0
source

Source: https://habr.com/ru/post/899745/


All Articles