Does someone know a good way to display the sorting icons in the header of a JTable, without using the build in sort functionality?
The sorting is done by the table model (actually a database) and not by the JTable itself. Thats why the automatic display of the icons doesn't work. Maybe one can insert a dummy RowSorter that does nothing, but makes the sort icons appear?
I found a better Solution
I just wrote my own RowSorter, so that the sorting does not have any effect, but redirects the sorting request to the model instead. That way the sort order is displayed by the look and feel itself. Some Pseudocode:
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import javax.swing.RowSorter;
import xyz.SortableTableModel;
public class MyRowSorter<M extends SortableTableModel> extends RowSorter<M> {
private M tableModel;
private List<? extends SortKey> sortKeys = new LinkedList<>();
public MyRowSorter(M tableModel) {
this.tableModel = tableModel;
}
@Override
public M getModel() {
return tableModel;
}
@Override
public void toggleSortOrder(int column) {
// redirecting sort request to model and modification of sortKeys
List<? extends SortKey> newSortKeys = ...;
setSortKeys(newSortKeys);
}
@Override
public int convertRowIndexToModel(int index) {
return index; // will always be the same
}
@Override
public int convertRowIndexToView(int index) {
return index; // will always be the same
}
@Override
public void setSortKeys(List<? extends SortKey> keys) {
if (keys == null) {
sortKeys = Collections.EMPTY_LIST;
} else {
sortKeys = Collections.unmodifiableList(keys);
}
fireSortOrderChanged();
}
@Override
public List<? extends SortKey> getSortKeys() {
return sortKeys;
}
@Override
public int getViewRowCount() {
return tableModel.getRowCount();
}
@Override
public int getModelRowCount() {
return tableModel.getRowCount();
}
// no need for any implementation
@Override public void modelStructureChanged() { }
@Override public void allRowsChanged() { }
@Override public void rowsInserted(int firstRow, int endRow) { }
@Override public void rowsDeleted(int firstRow, int endRow) { }
@Override public void rowsUpdated(int firstRow, int endRow) { }
@Override public void rowsUpdated(int firstRow, int endRow, int column) { }
}