Reading posts on similar questions (like @mKorbel suggested) and experimenting myself I've managed to find a solution.
The answer for the main question would be: Use setSortable(int index, boolean sortable)
method of DefaultRowSorter. Seems obvious but what is interesting, is that this method disables sorting of a column when using toggleSortOrder(int index)
of RowSorter but it's ignored when using sort()
method of DefaultRowSorter. Is that a kind of inconsistency? Anyway this leaves the door open for a trick. Now I can do:
for (int i=0 ; i<table.getColumnCount() ; i++) {
sorter.setSortable(i, false);
}
...and voila - the table cannot be sorted by clicking table headers anymore, but it can be sorted programatically. If anyone faces a weird requirement of hiding those sort order indicator icons like I have, there are to ways. First will take a global effect and I don't like it - set the corresponding properties to UIManager.
UIManager.put("Table.ascendingSortIcon", new EmptyIcon());
UIManager.put("Table.descendingSortIcon", new EmptyIcon());
The better one is to decorate default renderer of the TableHeader:
final TableCellRenderer defaultRenderer = table.getTableHeader().getDefaultRenderer();
table.getTableHeader().setDefaultRenderer(new TableCellRenderer() {
@Override
public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus,
int row, int column) {
JLabel label = (JLabel)defaultRenderer.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
label.setIcon(null);
return label;
}
});