Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to restore the original row order with JTable's row sorter?

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?

like image 874
JooMing Avatar asked Nov 28 '22 15:11

JooMing


2 Answers

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

like image 60
kleopatra Avatar answered Dec 08 '22 00:12

kleopatra


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().

like image 41
trashgod Avatar answered Dec 08 '22 00:12

trashgod