I've enabled sorting in JTable with setAutoCreateRowSorter method. Mouse clicks on the column headers will switch between ascending and descending order, but I would like to switch it between ascending, descending and the original (unsorted) row order. Any hints how to achieve this?
The mapping of a mouse click to changing the sort state is implemented in BasicTableHeaderUI and happens exclusively via the RowSorter's toggleSortOrder(columnIndex). It's default behaviour is to switch
UNSORTED --> ASCENDING --> DESCENDING --> ASCENDING --
that is, no way back into the UNSORTED. If the requirement is to simply widen the circle into:
UNSORTED --> ASCENDING --> DESCENDING -- UNSORTED --> ASCENDING --
the way to go is to subclass TableRowSorter and override its toggleSortOrder accordingly
/**
* @inherited <p>
*/
@Override
public void toggleSortOrder(int column) {
List<? extends SortKey> sortKeys = getSortKeys();
if (sortKeys.size() > 0) {
if (sortKeys.get(0).getSortOrder() == SortOrder.DESCENDING) {
setSortKeys(null);
return;
}
}
super.toggleSortOrder(column);
}
Note: this is a bit simplified as it doesn't account for n-ary sorted columns, see SwingX DefaultSortController for a full version. Or use SwingX to start with, its JXTable has api to configure the sorting cycle like
table.setSortOrderCycle(ASCENDING, DESCENDING, UNSORTED);
Cheers Jeanette
If you're using the DefaultRowSorter
: "An empty sortKeys
list indicates that the view should [be] unsorted, the same as the model."
RowSorter rs = table.getRowSorter();
rs.setSortKeys(null);
Addendum: Note that "null
is a shorthand for specifying an empty list" in setSortKeys()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With