How to use JTable’s row classifier to restore the original row order?
I have enabled sorting in JTable using the setautocreaterowsorter method Clicking the column header will switch between ascending and descending, but I want to switch between ascending, descending and original (Unsorted) row order Any tips on how to achieve this goal?
Solution
The mapping from mouse click to change sorting status is implemented in the basic table header UI, and only through the togglesortorder (columnindex) of rowsorter Its default behavior is switching
Unsorted – > ascending – > descending – > ascending –
In other words, there is no way to go back to unsorted If required, simply expand the circle to:
Unsorted – > ascending – > descending – unsorted – > rising –
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 because it does not consider the n-ary sequence. Please refer to swingx defaultsortcontroller for the full version Or start with swingx, whose jxtable has an API to configure the sort cycle
table.setSortOrderCycle(ASCENDING,DESCENDING,UNSORTED);
Cheers, Janet