Google Tag Manager

2017/08/22

Apply sort order cycle with ascending, descending, and unsorted in TableRowSorter with multi-key sorting

Summary

A three-state sorter(ascending, descending, none) example. Primary sort column is highlighted and the next ones have their sort-order number in brackets as shown on the screenshot below.
  • Left click: Change sort order in ascending, descending, unsorted
  • Right click: Unsorted

Code

/**
 * @author ssr
 */
jTable1.getTableHeader().setDefaultRenderer(new TestTableCellRenderer(jTable1));
TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(jTable1.getModel()) {
  @Override
  public void toggleSortOrder(int column) {
    int keyIndex;
    if (column >= 0 && column < getModelWrapper().getColumnCount() && isSortable(column)) {
      List<RowSorter.SortKey> keys = new ArrayList<>(getSortKeys());
      boolean found = false;
      for (keyIndex = 0; keyIndex < keys.size(); keyIndex++) {
        RowSorter.SortKey sortKey = keys.get(keyIndex);
        if (sortKey.getColumn() == column) {
          found = true;
          break;
        }
      }
      if (isSortable(column)) {
        if (!found) {
          // Key doesn't exist
          RowSorter.SortKey sortKey = new RowSorter.SortKey(column, SortOrder.ASCENDING);
          keys.add(sortKey);
          System.out.println("ADDED: ");
          keys.stream().forEach(k -> System.out.println(k.getColumn() + ":" + k.getSortOrder()));
        } else {
          RowSorter.SortKey sortKey = keys.get(keyIndex);
          if (sortKey.getSortOrder() == SortOrder.DESCENDING) {
            keys.remove(keyIndex);
            System.out.println("REMOVED: ");
            keys.stream().forEach(k -> System.out.println(k.getColumn() + ":" + k.getSortOrder()));
          } else {
            keys.set(keyIndex, new RowSorter.SortKey(
                column, sortKey.getSortOrder() == SortOrder.ASCENDING
                  ? SortOrder.DESCENDING
                  : SortOrder.ASCENDING));
            System.out.println("MODIFIED: ");
            keys.stream().forEach(k -> System.out.println(k.getColumn() + ":" + k.getSortOrder()));
          }
        }
        if (keys.size() > getMaxSortKeys()) {
          keys = keys.subList(0, getMaxSortKeys());
        }
        setSortKeys(keys);
      }
    }
  }
};
sorter.setMaxSortKeys(4);
jTable1.setRowSorter(sorter);

References