I have an JTable which is using RowSorter(Java 1.6) and I am using the look and feel which was implemented using Java 1.4, when RowSorter was not added in Java. Now my problem is: when I click on the table header, table gets sorted but the RosSorter icon does not appear on the Table header. I need that icon somehow and I can not upgrade the existing look and feel. Any help ?
The basic approach is to wrap the renderer that is supplied by the LAF, let it configure the rendering component and additionally make it paint a sort icon as appropriate. Something like:
final TableCellRenderer r = table.getTableHeader().getDefaultRenderer();
TableCellRenderer wrapper = new TableCellRenderer() {
@Override
public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus,
int row, int column) {
Component comp = r.getTableCellRendererComponent(table, value, isSelected,
hasFocus, row, column);
if (comp instanceof JLabel) {
JLabel label = (JLabel) comp;
label.setIcon(getSortIcon(table, column));
}
return comp;
}
/**
* Implements the logic to choose the appropriate icon.
*/
private Icon getSortIcon(JTable table, int column) {
SortOrder sortOrder = getColumnSortOrder(table, column);
if (SortOrder.UNSORTED == sortOrder) {
return null;
}
return SortOrder.ASCENDING == sortOrder ? ascendingIcon : descendingIcon;
}
private SortOrder getColumnSortOrder(JTable table, int column) {
if (table == null || table.getRowSorter() == null) {
return SortOrder.UNSORTED;
}
List<? extends SortKey> keys = table.getRowSorter().getSortKeys();
if (keys.size() > 0) {
SortKey key = keys.get(0);
if (key.getColumn() == table.convertColumnIndexToModel(column)) {
return key.getSortOrder();
}
}
return SortOrder.UNSORTED;
}
};
table.getTableHeader().setDefaultRenderer(wrapper);
That's the easiest case, working if the rendering component is-a JLabel and doesn't use its icon property somehow else.