Google Tag Manager

2008/09/16

JTable Tri-state row sorting (cycle through ascending descending unsorted)

Code

TableModel model = new DefaultTableModel();
JTable table = new JTable(model);
//sort toggles ascending descending unsorted (like TableSorter.java)
TableRowSorter< TableModel > sorter = new TableRowSorter< TableModel >(model) {
  @Override
  public void toggleSortOrder(int column) {
    if(column >= 0 && column < getModelWrapper().getColumnCount() && isSortable(column)) {
      List< SortKey > keys = new ArrayList< SortKey >(getSortKeys());
      if(!keys.isEmpty()) {
        SortKey sortKey = keys.get(0);
        if(sortKey.getColumn()==column && sortKey.getSortOrder()==SortOrder.DESCENDING) {
          setSortKeys(null);
          return;
        }
      }
    }
    super.toggleSortOrder(column);
  }
};
table.setRowSorter(sorter);

References

No comments:

Post a Comment