I have a number of JXTables which all have the same columns (but different data). You can sort the data by clicking on one the header of one of the columns. What I want now, is that the other tables are sorted the same way when clicking on the header of one of the table.
You could define a mediator class that references each JTable
's RowSorter
and registers itself as a RowSorterListener
with each sorter. When a given sorter changes you could retrieve its current list of sort keys using getSortKets()
and pass them to every other sorter using setSortKeys(List<? extends SortKey>)
.
Example
First we define the mediator 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 a given 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);
}
}
}
}
I would not do that, because it takes control away from the user: s/he may want to have the tables sorted differently, to compare different pieces of data.
Instead, add a "Sort By" option to your View menu. Changing this option will sort all tables, but then leave them alone unless the user wants to sort a specific table.