4
votes

Is it possible to disable manual sorting on a JTable after adding a sorter? So I have a JTable that has the following sorter attached to it (basically sorts by column 3 when the table is initialised):

JTable jTable = new JTable();
RowSorter<TableModel> sorter = new TableRowSorter<TableModel>(jTable.getModel());
List<RowSorter.SortKey> sortKeys = new ArrayList<RowSorter.SortKey>();
sortKeys.add(new RowSorter.SortKey(3, SortOrder.DESCENDING));
sorter.setSortKeys(sortKeys); 
jTable.setRowSorter(sorter);

This works fine, however the user is still able to click on the column headers in the table and sort by any of the columns, which I want to disable. Is this possible?

3
You might like to check @mkorbel's suggests from this similar questions - MadProgrammer
reading Default/RowSorter's api doc might help :-) - kleopatra

3 Answers

15
votes

You can use the setSortable method of TableRowSorter as below:

sorter.setSortable(0, false); 

to make column 0 non-sortable. You can apply it on the column according to your requirement.

6
votes

Alternatively, you can set your sortable and non-sortable columns like this:

TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(table.getModel()) {
    @Override
    public boolean isSortable(int column) {
        if(column < 2)
            return true;
        else 
            return false;
    };
};
table.setRowSorter(sorter);
4
votes

I ran into the same problem recently, and found the perfect solution to this problem. The TableHeader can simply be disabled.

jTable.getTableHeader().setEnabled(false);

This way, the sorter works perfectly on any of the columns, but manual sorting is prevented by click on the Column Headers.

Hope this helps the future users who might want to have a look at it.