// There is no-where else to put this.
// Add a mouse listener to the Table to trigger a table sort
// when a column heading is clicked in the JTable.
public void addMouseListenerToHeaderInTable(JTable table) {
final TableSorter sorter = this;
final JTable tableView = table;
tableView.getTableHeader().setDefaultRenderer(unSortedRenderer);
tableView.setColumnSelectionAllowed(false);
MouseAdapter listMouseListener = new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
TableColumnModel columnModel = tableView.getColumnModel();
int viewColumn = columnModel.getColumnIndexAtX(e.getX());
int column = tableView.convertColumnIndexToModel(viewColumn);
if (e.getClickCount() == 1 && column != -1) {
if (singleSortingColumn == column)
ascending = !ascending;
else
ascending = true;
sorter.sortByColumn(column);
singleSortingColumn = column;
// setting renderer
for (int i = 0; i < columnModel.getColumnCount(); i++)
columnModel.getColumn(i).setHeaderRenderer(unSortedRenderer);
if (ascending)
sortedRenderer.setIconType(SortedTableHeaderRenderer.ASCENDING);
else
sortedRenderer.setIconType(SortedTableHeaderRenderer.DESCENDING);
columnModel.getColumn(column).setHeaderRenderer(sortedRenderer);
}
}
};
JTableHeader th = tableView.getTableHeader();
th.addMouseListener(listMouseListener);
}