001 package nl.cwi.sen1.gui.plugin.data; 002 003 import java.awt.Color; 004 import java.awt.Component; 005 import java.awt.Graphics; 006 import java.awt.event.MouseAdapter; 007 import java.awt.event.MouseEvent; 008 import java.awt.event.MouseListener; 009 import java.util.ArrayList; 010 import java.util.Arrays; 011 import java.util.Comparator; 012 import java.util.HashMap; 013 import java.util.Iterator; 014 import java.util.List; 015 import java.util.Map; 016 017 import javax.swing.Icon; 018 import javax.swing.JLabel; 019 import javax.swing.JTable; 020 import javax.swing.event.TableModelEvent; 021 import javax.swing.event.TableModelListener; 022 import javax.swing.table.AbstractTableModel; 023 import javax.swing.table.JTableHeader; 024 import javax.swing.table.TableCellRenderer; 025 import javax.swing.table.TableColumnModel; 026 import javax.swing.table.TableModel; 027 028 /** 029 * TableSorter is a decorator for TableModels; adding sorting functionality to a 030 * supplied TableModel. TableSorter does not store or copy the data in its 031 * TableModel; instead it maintains a map from the row indexes of the view to 032 * the row indexes of the model. As requests are made of the sorter (like 033 * getValueAt(row, col)) they are passed to the underlying model after the row 034 * numbers have been translated via the internal mapping array. This way, the 035 * TableSorter appears to hold another copy of the table with the rows in a 036 * different order. <p/> TableSorter registers itself as a listener to the 037 * underlying model, just as the JTable itself would. Events recieved from the 038 * model are examined, sometimes manipulated (typically widened), and then 039 * passed on to the TableSorter's listeners (typically the JTable). If a change 040 * to the model has invalidated the order of TableSorter's rows, a note of this 041 * is made and the sorter will resort the rows the next time a value is 042 * requested. <p/> When the tableHeader property is set, either by using the 043 * setTableHeader() method or the two argument constructor, the table header may 044 * be used as a complete UI for TableSorter. The default renderer of the 045 * tableHeader is decorated with a renderer that indicates the sorting status of 046 * each column. In addition, a mouse listener is installed with the following 047 * behavior: 048 * <ul> 049 * <li> Mouse-click: Clears the sorting status of all other columns and advances 050 * the sorting status of that column through three values: {NOT_SORTED, 051 * ASCENDING, DESCENDING} (then back to NOT_SORTED again). 052 * <li> SHIFT-mouse-click: Clears the sorting status of all other columns and 053 * cycles the sorting status of the column through the same three values, in the 054 * opposite order: {NOT_SORTED, DESCENDING, ASCENDING}. 055 * <li> CONTROL-mouse-click and CONTROL-SHIFT-mouse-click: as above except that 056 * the changes to the column do not cancel the statuses of columns that are 057 * already sorting - giving a way to initiate a compound sort. 058 * </ul> 059 * <p/> This is a long overdue rewrite of a class of the same name that first 060 * appeared in the swing table demos in 1997. 061 * 062 * @author Philip Milne 063 * @author Brendon McLean 064 * @author Dan van Enckevort 065 * @author Parwinder Sekhon 066 * @version 2.0 02/27/04 067 */ 068 069 public class TableSorter extends AbstractTableModel { 070 protected TableModel tableModel; 071 072 public static final int DESCENDING = -1; 073 public static final int NOT_SORTED = 0; 074 public static final int ASCENDING = 1; 075 076 private static Directive EMPTY_DIRECTIVE = new Directive(-1, NOT_SORTED); 077 078 public static final Comparator COMPARABLE_COMAPRATOR = new Comparator() { 079 public int compare(Object o1, Object o2) { 080 return ((Comparable) o1).compareTo(o2); 081 } 082 }; 083 084 public static final Comparator LEXICAL_COMPARATOR = new Comparator() { 085 public int compare(Object o1, Object o2) { 086 return o1.toString().compareTo(o2.toString()); 087 } 088 }; 089 090 private Row[] viewToModel; 091 private int[] modelToView; 092 093 private JTableHeader tableHeader; 094 private MouseListener mouseListener; 095 private TableModelListener tableModelListener; 096 private Map<Class, Comparator> columnComparators = new HashMap<Class, Comparator>(); 097 private List<Directive> sortingColumns = new ArrayList<Directive>(); 098 099 public TableSorter() { 100 this.mouseListener = new MouseHandler(); 101 this.tableModelListener = new TableModelHandler(); 102 } 103 104 public TableSorter(TableModel tableModel) { 105 this(); 106 setTableModel(tableModel); 107 } 108 109 public TableSorter(TableModel tableModel, JTableHeader tableHeader) { 110 this(); 111 setTableHeader(tableHeader); 112 setTableModel(tableModel); 113 } 114 115 private void clearSortingState() { 116 viewToModel = null; 117 modelToView = null; 118 } 119 120 public TableModel getTableModel() { 121 return tableModel; 122 } 123 124 public void setTableModel(TableModel tableModel) { 125 if (this.tableModel != null) { 126 this.tableModel.removeTableModelListener(tableModelListener); 127 } 128 129 this.tableModel = tableModel; 130 if (this.tableModel != null) { 131 this.tableModel.addTableModelListener(tableModelListener); 132 } 133 134 clearSortingState(); 135 fireTableStructureChanged(); 136 } 137 138 public JTableHeader getTableHeader() { 139 return tableHeader; 140 } 141 142 public void setTableHeader(JTableHeader tableHeader) { 143 if (this.tableHeader != null) { 144 this.tableHeader.removeMouseListener(mouseListener); 145 TableCellRenderer defaultRenderer = this.tableHeader 146 .getDefaultRenderer(); 147 if (defaultRenderer instanceof SortableHeaderRenderer) { 148 this.tableHeader 149 .setDefaultRenderer(((SortableHeaderRenderer) defaultRenderer).tableCellRenderer); 150 } 151 } 152 this.tableHeader = tableHeader; 153 if (this.tableHeader != null) { 154 this.tableHeader.addMouseListener(mouseListener); 155 this.tableHeader.setDefaultRenderer(new SortableHeaderRenderer( 156 this.tableHeader.getDefaultRenderer())); 157 } 158 } 159 160 public boolean isSorting() { 161 return sortingColumns.size() != 0; 162 } 163 164 private Directive getDirective(int column) { 165 for (int i = 0; i < sortingColumns.size(); i++) { 166 Directive directive = sortingColumns.get(i); 167 if (directive.column == column) { 168 return directive; 169 } 170 } 171 return EMPTY_DIRECTIVE; 172 } 173 174 public int getSortingStatus(int column) { 175 return getDirective(column).direction; 176 } 177 178 private void sortingStatusChanged() { 179 clearSortingState(); 180 fireTableDataChanged(); 181 if (tableHeader != null) { 182 tableHeader.repaint(); 183 } 184 } 185 186 public void setSortingStatus(int column, int status) { 187 Directive directive = getDirective(column); 188 if (directive != EMPTY_DIRECTIVE) { 189 sortingColumns.remove(directive); 190 } 191 if (status != NOT_SORTED) { 192 sortingColumns.add(new Directive(column, status)); 193 } 194 sortingStatusChanged(); 195 } 196 197 protected Icon getHeaderRendererIcon(int column, int size) { 198 Directive directive = getDirective(column); 199 if (directive == EMPTY_DIRECTIVE) { 200 return null; 201 } 202 return new Arrow(directive.direction == DESCENDING, size, 203 sortingColumns.indexOf(directive)); 204 } 205 206 private void cancelSorting() { 207 sortingColumns.clear(); 208 sortingStatusChanged(); 209 } 210 211 public void setColumnComparator(Class type, Comparator comparator) { 212 if (comparator == null) { 213 columnComparators.remove(type); 214 } else { 215 columnComparators.put(type, comparator); 216 } 217 } 218 219 protected Comparator getComparator(int column) { 220 Class columnType = tableModel.getColumnClass(column); 221 Comparator comparator = columnComparators.get(columnType); 222 if (comparator != null) { 223 return comparator; 224 } 225 if (Comparable.class.isAssignableFrom(columnType)) { 226 return COMPARABLE_COMAPRATOR; 227 } 228 return LEXICAL_COMPARATOR; 229 } 230 231 private Row[] getViewToModel() { 232 if (viewToModel == null) { 233 int tableModelRowCount = tableModel.getRowCount(); 234 viewToModel = new Row[tableModelRowCount]; 235 for (int row = 0; row < tableModelRowCount; row++) { 236 viewToModel[row] = new Row(row); 237 } 238 239 if (isSorting()) { 240 Arrays.sort(viewToModel); 241 } 242 } 243 return viewToModel; 244 } 245 246 public int modelIndex(int viewIndex) { 247 return getViewToModel()[viewIndex].modelIndex; 248 } 249 250 private int[] getModelToView() { 251 if (modelToView == null) { 252 int n = getViewToModel().length; 253 modelToView = new int[n]; 254 for (int i = 0; i < n; i++) { 255 modelToView[modelIndex(i)] = i; 256 } 257 } 258 return modelToView; 259 } 260 261 // TableModel interface methods 262 263 public int getRowCount() { 264 return (tableModel == null) ? 0 : tableModel.getRowCount(); 265 } 266 267 public int getColumnCount() { 268 return (tableModel == null) ? 0 : tableModel.getColumnCount(); 269 } 270 271 public String getColumnName(int column) { 272 return tableModel.getColumnName(column); 273 } 274 275 public Class getColumnClass(int column) { 276 return tableModel.getColumnClass(column); 277 } 278 279 public boolean isCellEditable(int row, int column) { 280 return tableModel.isCellEditable(modelIndex(row), column); 281 } 282 283 public Object getValueAt(int row, int column) { 284 return tableModel.getValueAt(modelIndex(row), column); 285 } 286 287 public void setValueAt(Object aValue, int row, int column) { 288 tableModel.setValueAt(aValue, modelIndex(row), column); 289 } 290 291 // Helper classes 292 293 private class Row implements Comparable { 294 private int modelIndex; 295 296 public Row(int index) { 297 this.modelIndex = index; 298 } 299 300 public int compareTo(Object o) { 301 int row1 = modelIndex; 302 int row2 = ((Row) o).modelIndex; 303 304 for (Iterator<Directive> it = sortingColumns.iterator(); it.hasNext();) { 305 Directive directive = it.next(); 306 int column = directive.column; 307 Object o1 = tableModel.getValueAt(row1, column); 308 Object o2 = tableModel.getValueAt(row2, column); 309 310 int comparison = 0; 311 // Define null less than everything, except null. 312 if (o1 == null && o2 == null) { 313 comparison = 0; 314 } else if (o1 == null) { 315 comparison = -1; 316 } else if (o2 == null) { 317 comparison = 1; 318 } else { 319 comparison = getComparator(column).compare(o1, o2); 320 } 321 if (comparison != 0) { 322 return directive.direction == DESCENDING ? -comparison 323 : comparison; 324 } 325 } 326 return 0; 327 } 328 } 329 330 private class TableModelHandler implements TableModelListener { 331 public void tableChanged(TableModelEvent e) { 332 // If we're not sorting by anything, just pass the event along. 333 if (!isSorting()) { 334 clearSortingState(); 335 fireTableChanged(e); 336 return; 337 } 338 339 // If the table structure has changed, cancel the sorting; the 340 // sorting columns may have been either moved or deleted from 341 // the model. 342 if (e.getFirstRow() == TableModelEvent.HEADER_ROW) { 343 cancelSorting(); 344 fireTableChanged(e); 345 return; 346 } 347 348 // We can map a cell event through to the view without widening 349 // when the following conditions apply: 350 // 351 // a) all the changes are on one row (e.getFirstRow() == 352 // e.getLastRow()) and, 353 // b) all the changes are in one column (column != 354 // TableModelEvent.ALL_COLUMNS) and, 355 // c) we are not sorting on that column (getSortingStatus(column) == 356 // NOT_SORTED) and, 357 // d) a reverse lookup will not trigger a sort (modelToView != null) 358 // 359 // Note: INSERT and DELETE events fail this test as they have column 360 // == ALL_COLUMNS. 361 // 362 // The last check, for (modelToView != null) is to see if 363 // modelToView 364 // is already allocated. If we don't do this check; sorting can 365 // become 366 // a performance bottleneck for applications where cells 367 // change rapidly in different parts of the table. If cells 368 // change alternately in the sorting column and then outside of 369 // it this class can end up re-sorting on alternate cell updates - 370 // which can be a performance problem for large tables. The last 371 // clause avoids this problem. 372 int column = e.getColumn(); 373 if (e.getFirstRow() == e.getLastRow() 374 && column != TableModelEvent.ALL_COLUMNS 375 && getSortingStatus(column) == NOT_SORTED 376 && modelToView != null) { 377 int viewIndex = getModelToView()[e.getFirstRow()]; 378 fireTableChanged(new TableModelEvent(TableSorter.this, 379 viewIndex, viewIndex, column, e.getType())); 380 return; 381 } 382 383 // Something has happened to the data that may have invalidated the 384 // row order. 385 clearSortingState(); 386 fireTableDataChanged(); 387 return; 388 } 389 } 390 391 private class MouseHandler extends MouseAdapter { 392 public void mouseClicked(MouseEvent e) { 393 JTableHeader h = (JTableHeader) e.getSource(); 394 TableColumnModel columnModel = h.getColumnModel(); 395 int viewColumn = columnModel.getColumnIndexAtX(e.getX()); 396 int column = columnModel.getColumn(viewColumn).getModelIndex(); 397 if (column != -1) { 398 int status = getSortingStatus(column); 399 if (!e.isControlDown()) { 400 cancelSorting(); 401 } 402 // Cycle the sorting states through {NOT_SORTED, ASCENDING, 403 // DESCENDING} or 404 // {NOT_SORTED, DESCENDING, ASCENDING} depending on whether 405 // shift is pressed. 406 status = status + (e.isShiftDown() ? -1 : 1); 407 status = (status + 4) % 3 - 1; // signed mod, returning {-1, 0, 408 // 1} 409 setSortingStatus(column, status); 410 } 411 } 412 } 413 414 private static class Arrow implements Icon { 415 private boolean descending; 416 private int size; 417 private int priority; 418 419 public Arrow(boolean descending, int size, int priority) { 420 this.descending = descending; 421 this.size = size; 422 this.priority = priority; 423 } 424 425 public void paintIcon(Component c, Graphics g, int x, int y) { 426 Color color = c == null ? Color.GRAY : c.getBackground(); 427 // In a compound sort, make each succesive triangle 20% 428 // smaller than the previous one. 429 int dx = (int) (size / 2 * Math.pow(0.8, priority)); 430 int dy = descending ? dx : -dx; 431 // Align icon (roughly) with font baseline. 432 y = y + 5 * size / 6 + (descending ? -dy : 0); 433 int shift = descending ? 1 : -1; 434 g.translate(x, y); 435 436 // Right diagonal. 437 g.setColor(color.darker()); 438 g.drawLine(dx / 2, dy, 0, 0); 439 g.drawLine(dx / 2, dy + shift, 0, shift); 440 441 // Left diagonal. 442 g.setColor(color.brighter()); 443 g.drawLine(dx / 2, dy, dx, 0); 444 g.drawLine(dx / 2, dy + shift, dx, shift); 445 446 // Horizontal line. 447 if (descending) { 448 g.setColor(color.darker().darker()); 449 } else { 450 g.setColor(color.brighter().brighter()); 451 } 452 g.drawLine(dx, 0, 0, 0); 453 454 g.setColor(color); 455 g.translate(-x, -y); 456 } 457 458 public int getIconWidth() { 459 return size; 460 } 461 462 public int getIconHeight() { 463 return size; 464 } 465 } 466 467 private class SortableHeaderRenderer implements TableCellRenderer { 468 private TableCellRenderer tableCellRenderer; 469 470 public SortableHeaderRenderer(TableCellRenderer tableCellRenderer) { 471 this.tableCellRenderer = tableCellRenderer; 472 } 473 474 public Component getTableCellRendererComponent(JTable table, 475 Object value, boolean isSelected, boolean hasFocus, int row, 476 int column) { 477 Component c = tableCellRenderer.getTableCellRendererComponent( 478 table, value, isSelected, hasFocus, row, column); 479 if (c instanceof JLabel) { 480 JLabel l = (JLabel) c; 481 l.setHorizontalTextPosition(JLabel.LEFT); 482 int modelColumn = table.convertColumnIndexToModel(column); 483 l.setIcon(getHeaderRendererIcon(modelColumn, l.getFont() 484 .getSize())); 485 } 486 return c; 487 } 488 } 489 490 private static class Directive { 491 private int column; 492 private int direction; 493 494 public Directive(int column, int direction) { 495 this.column = column; 496 this.direction = direction; 497 } 498 } 499 }