views:

306

answers:

2

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.

+2  A: 

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);
        }
      }
    }
  }
Adamski
Problem is the table doesn't seem to have any rowsorters. Even the 'sortManager' is null. However, the sorting works when I click the column header.
Fortega
I think that's because it is a JXTable. I thought the sorting was handled by the Table, but I'm not sure anymore now.
Fortega
Ah sorry - Didn't notice it was JXTable. If you're using JDK 1.6 I'd recommend moving to JTable which gives you more performant sorting.
Adamski
A: 

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.

kdgregory
There are instances where it is important to keep two tables sorted in the same manner; for example I've used this approach when building a "diff" view consisting of a left and right JTable where the scroll bars and sort orders have to remain in sync.
Adamski
Sure, there are times when this is useful. But most of the time it's a really bad idea from a user experience perspective. It violates the "principle of least astonishment."
kdgregory