JXTable listens for sorting and sorting a similar table in the same way

I have several JXTables that all have the same columns (but different data). You can sort the data by clicking on one heading of one of the columns. Now I want other tables to sort the same way when I click on the header of one of the tables.

+4
source share
2 answers

You can define an intermediary class that references every JTable RowSorter and registers as a RowSorterListener with each sorter. When this sorter changes, you can get the current list of sort keys using getSortKets() and pass them to each sorter using setSortKeys(List<? extends SortKey>) .

Example

First, we define the mediation class:

 public class SortMediator implements RowSorterListener { private final List<RowSorter> sorters; private boolean changing; public void addRowSorter(RowSorter sorter) { this.sorters.add(sorter); } public void sorterChanged(RowSorterEvent e) { ... } } 

Now we implement sorterChanged(RowSorterEvent e) to respond to the specified sorter event:

  public void sorterChanged(RowSorterEvent e) { // The changing flag prevents an infinite loop after responding to the inital // sort event. if (!changing) { changing = true; RowSorter changedSorter = e.getSource(); List<? extends SortKey> keys = changedSorter.getKeys(); for (RowSorter sorter : sorters) { if (sorter != changedSorter) { // Install new sort keys, which will cause the sorter to re-sort. // The changing flag will prevent the mediator from reacting to this. sorter.setSortKeys(keys); } } } } 
+4
source

I would not do this because it takes control from the user: s / he might want tables sorted differently to compare different pieces of data.

Instead, add the option "Sort by" in the "View" menu. Changing this option will sort all tables, but then leave them alone if the user does not want to sort a specific table.

0
source

All Articles