Debian Codegraph @

src/dr/app/gui/table/TableSorter.java

raw symbols SCIP
1 /*
2 * TableSorter.java
3 *
4 * Copyright (c) 2002-2015 Alexei Drummond, Andrew Rambaut and Marc Suchard
5 *
6 * This file is part of BEAST.
7 * See the NOTICE file distributed with this work for additional
8 * information regarding copyright ownership and licensing.
9 *
10 * BEAST is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU Lesser General Public License as
12 * published by the Free Software Foundation; either version 2
13 * of the License, or (at your option) any later version.
14 *
15 * BEAST is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU Lesser General Public License for more details.
19 *
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with BEAST; if not, write to the
22 * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
23 * Boston, MA 02110-1301 USA
24 */
25
26 package dr.app.gui.table;
27
28 import jam.util.IconUtils;
29
30 import javax.swing.*;
31 import javax.swing.event.TableModelEvent;
32 import javax.swing.event.TableModelListener;
33 import javax.swing.table.*;
34 import java.awt.*;
35 import java.awt.event.MouseAdapter;
36 import java.awt.event.MouseEvent;
37 import java.awt.event.MouseListener;
38 import java.util.*;
39 import java.util.List;
40
41 /**
42 * TableSorter is a decorator for TableModels; adding sorting
43 * functionality to a supplied TableModel. TableSorter does
44 * not store or copy the data in its TableModel; instead it maintains
45 * a map from the row indexes of the view to the row indexes of the
46 * model. As requests are made of the sorter (like getValueAt(row, col))
47 * they are passed to the underlying model after the row numbers
48 * have been translated via the internal mapping array. This way,
49 * the TableSorter appears to hold another copy of the table
50 * with the rows in a different order.
51 * <p/>
52 * TableSorter registers itself as a listener to the underlying model,
53 * just as the JTable itself would. Events recieved from the model
54 * are examined, sometimes manipulated (typically widened), and then
55 * passed on to the TableSorter's listeners (typically the JTable).
56 * If a change to the model has invalidated the order of TableSorter's
57 * rows, a note of this is made and the sorter will resort the
58 * rows the next time a value is requested.
59 * <p/>
60 * When the tableHeader property is set, either by using the
61 * setTableHeader() method or the two argument constructor, the
62 * table header may be used as a complete UI for TableSorter.
63 * The default renderer of the tableHeader is decorated with a renderer
64 * that indicates the sorting status of each column. In addition,
65 * a mouse listener is installed with the following behavior:
66 * <ul>
67 * <li>
68 * Mouse-click: Clears the sorting status of all other columns
69 * and advances the sorting status of that column through three
70 * values: {NOT_SORTED, ASCENDING, DESCENDING} (then back to
71 * NOT_SORTED again).
72 * <li>
73 * SHIFT-mouse-click: Clears the sorting status of all other columns
74 * and cycles the sorting status of the column through the same
75 * three values, in the opposite order: {NOT_SORTED, DESCENDING, ASCENDING}.
76 * <li>
77 * CONTROL-mouse-click and CONTROL-SHIFT-mouse-click: as above except
78 * that the changes to the column do not cancel the statuses of columns
79 * that are already sorting - giving a way to initiate a compound
80 * sort.
81 * </ul>
82 * <p/>
83 * This is a long overdue rewrite of a class of the same name that
84 * first appeared in the swing table demos in 1997.
85 *
86 * @author Philip Milne
87 * @author Brendon McLean
88 * @author Dan van Enckevort
89 * @author Parwinder Sekhon
90 * @version 2.0 02/27/04
91 */
92
93 public class TableSorter extends AbstractTableModel {
94 /**
95 *
96 */
97 private static final long serialVersionUID = 2008453783405125906L;
98
99 protected TableModel tableModel;
100
101 public static final int DESCENDING = -1;
102 public static final int NOT_SORTED = 0;
103 public static final int ASCENDING = 1;
104
105 private static final Directive EMPTY_DIRECTIVE = new Directive(-1, NOT_SORTED);
106
107 public static final Comparator COMPARABLE_COMAPRATOR = new Comparator() {
108 public int compare(Object o1, Object o2) {
109 return ((Comparable) o1).compareTo(o2);
110 }
111 };
112 public static final Comparator LEXICAL_COMPARATOR = new Comparator() {
113 public int compare(Object o1, Object o2) {
114 return o1.toString().compareTo(o2.toString());
115 }
116 };
117
118 private Row[] viewToModel;
119 private int[] modelToView;
120
121 private JTableHeader tableHeader;
122 private final MouseListener mouseListener;
123 private final TableModelListener tableModelListener;
124 // (todo) nothing ever added to this map????
125 private final Map<Class, Comparator> columnComparators = new HashMap<Class, Comparator>();
126 private final List<Directive> sortingColumns = new ArrayList<Directive>();
127
128 public TableSorter() {
129 this.mouseListener = new MouseHandler();
130 this.tableModelListener = new TableModelHandler();
131 }
132
133 public TableSorter(TableModel tableModel) {
134 this();
135 setTableModel(tableModel);
136 }
137
138 public TableSorter(TableModel tableModel, JTableHeader tableHeader) {
139 this();
140 setTableHeader(tableHeader);
141 setTableModel(tableModel);
142 }
143
144 private void clearSortingState() {
145 viewToModel = null;
146 modelToView = null;
147 }
148
149 public TableModel getTableModel() {
150 return tableModel;
151 }
152
153 public void setTableModel(TableModel tableModel) {
154 if (this.tableModel != null) {
155 this.tableModel.removeTableModelListener(tableModelListener);
156 }
157
158 this.tableModel = tableModel;
159 if (this.tableModel != null) {
160 this.tableModel.addTableModelListener(tableModelListener);
161 }
162
163 clearSortingState();
164 fireTableStructureChanged();
165 }
166
167 public JTableHeader getTableHeader() {
168 return tableHeader;
169 }
170
171 public void setTableHeader(JTableHeader tableHeader) {
172 if (this.tableHeader != null) {
173 this.tableHeader.removeMouseListener(mouseListener);
174 TableCellRenderer defaultRenderer = this.tableHeader.getDefaultRenderer();
175 if (defaultRenderer instanceof SortableHeaderRenderer) {
176 this.tableHeader.setDefaultRenderer(((SortableHeaderRenderer) defaultRenderer).tableCellRenderer);
177 }
178 }
179 this.tableHeader = tableHeader;
180 if (this.tableHeader != null) {
181 this.tableHeader.addMouseListener(mouseListener);
182 this.tableHeader.setDefaultRenderer(
183 new SortableHeaderRenderer(this.tableHeader.getDefaultRenderer()));
184 }
185 }
186
187 public boolean isSorting() {
188 return sortingColumns.size() != 0;
189 }
190
191 private Directive getDirective(int column) {
192 for(Object sortingColumn : sortingColumns) {
193 Directive directive = (Directive) sortingColumn;
194 if( directive.column == column ) {
195 return directive;
196 }
197 }
198 return EMPTY_DIRECTIVE;
199 }
200
201 public int getSortingStatus(int column) {
202 return getDirective(column).direction;
203 }
204
205 private void sortingStatusChanged() {
206 clearSortingState();
207 fireTableDataChanged();
208 if (tableHeader != null) {
209 tableHeader.repaint();
210 }
211 }
212
213 public void setSortingStatus(int column, int status) {
214 Directive directive = getDirective(column);
215 if (directive != EMPTY_DIRECTIVE) {
216 sortingColumns.remove(directive);
217 }
218 if (status != NOT_SORTED) {
219 sortingColumns.add(new Directive(column, status));
220 }
221 sortingStatusChanged();
222 }
223
224 protected Icon getHeaderRendererIcon(int column, int size) {
225 Directive directive = getDirective(column);
226 if (directive == EMPTY_DIRECTIVE) {
227 return null;
228 }
229 if (sortAscendingIcon != null) {
230 if (directive.direction == DESCENDING) {
231 return sortDescendingIcon;
232 } else {
233 return sortAscendingIcon;
234 }
235 } else {
236 return new Arrow(directive.direction == DESCENDING, size, sortingColumns.indexOf(directive));
237 }
238 }
239
240 private void cancelSorting() {
241 sortingColumns.clear();
242 sortingStatusChanged();
243 }
244
245 public void setColumnComparator(Class type, Comparator comparator) {
246 if (comparator == null) {
247 columnComparators.remove(type);
248 } else {
249 columnComparators.put(type, comparator);
250 }
251 }
252
253 protected Comparator getComparator(int column) {
254 final Class columnType = tableModel.getColumnClass(column);
255 Comparator comparator = columnComparators.get(columnType);
256 if (comparator != null) {
257 return comparator;
258 }
259 if (Comparable.class.isAssignableFrom(columnType)) {
260 return COMPARABLE_COMAPRATOR;
261 }
262 return LEXICAL_COMPARATOR;
263 }
264
265 private Row[] getViewToModel() {
266 if (viewToModel == null) {
267 int tableModelRowCount = tableModel.getRowCount();
268 viewToModel = new Row[tableModelRowCount];
269 for (int row = 0; row < tableModelRowCount; row++) {
270 viewToModel[row] = new Row(row);
271 }
272
273 if (isSorting()) {
274 Arrays.sort(viewToModel);
275 }
276 }
277 return viewToModel;
278 }
279
280 public int modelIndex(int viewIndex) {
281 return getViewToModel()[viewIndex].modelIndex;
282 }
283
284 private int[] getModelToView() {
285 if (modelToView == null) {
286 int n = getViewToModel().length;
287 modelToView = new int[n];
288 for (int i = 0; i < n; i++) {
289 modelToView[modelIndex(i)] = i;
290 }
291 }
292 return modelToView;
293 }
294
295 // TableModel interface methods
296
297 public int getRowCount() {
298 return (tableModel == null) ? 0 : tableModel.getRowCount();
299 }
300
301 public int getColumnCount() {
302 return (tableModel == null) ? 0 : tableModel.getColumnCount();
303 }
304
305 public String getColumnName(int column) {
306 return tableModel.getColumnName(column);
307 }
308
309 public Class getColumnClass(int column) {
310 return tableModel.getColumnClass(column);
311 }
312
313 public boolean isCellEditable(int row, int column) {
314 return tableModel.isCellEditable(modelIndex(row), column);
315 }
316
317 public Object getValueAt(int row, int column) {
318 return tableModel.getValueAt(modelIndex(row), column);
319 }
320
321 public void setValueAt(Object aValue, int row, int column) {
322 tableModel.setValueAt(aValue, modelIndex(row), column);
323 }
324
325 // Helper classes
326
327 private class Row implements Comparable {
328 private final int modelIndex;
329
330 public Row(int index) {
331 this.modelIndex = index;
332 }
333
334 public int compareTo(Object o) {
335 int row1 = modelIndex;
336 int row2 = ((Row) o).modelIndex;
337
338 for( Directive directive : sortingColumns ) {
339 int column = directive.column;
340 Object o1 = tableModel.getValueAt(row1, column);
341 Object o2 = tableModel.getValueAt(row2, column);
342
343 int comparison;
344 // Define null less than everything, except null.
345 if( o1 == null && o2 == null ) {
346 comparison = 0;
347 } else if( o1 == null ) {
348 comparison = -1;
349 } else if( o2 == null ) {
350 comparison = 1;
351 } else {
352 comparison = getComparator(column).compare(o1, o2);
353 }
354 if( comparison != 0 ) {
355 return directive.direction == DESCENDING ? -comparison : comparison;
356 }
357 }
358 return 0;
359 }
360 }
361
362 private class TableModelHandler implements TableModelListener {
363 public void tableChanged(TableModelEvent e) {
364 // If we're not sorting by anything, just pass the event along.
365 if (!isSorting()) {
366 clearSortingState();
367 fireTableChanged(e);
368 return;
369 }
370
371 // If the table structure has changed, cancel the sorting; the
372 // sorting columns may have been either moved or deleted from
373 // the model.
374 if (e.getFirstRow() == TableModelEvent.HEADER_ROW) {
375 cancelSorting();
376 fireTableChanged(e);
377 return;
378 }
379
380 // We can map a cell event through to the view without widening
381 // when the following conditions apply:
382 //
383 // a) all the changes are on one row (e.getFirstRow() == e.getLastRow()) and,
384 // b) all the changes are in one column (column != TableModelEvent.ALL_COLUMNS) and,
385 // c) we are not sorting on that column (getSortingStatus(column) == NOT_SORTED) and,
386 // d) a reverse lookup will not trigger a sort (modelToView != null)
387 //
388 // Note: INSERT and DELETE events fail this test as they have column == ALL_COLUMNS.
389 //
390 // The last check, for (modelToView != null) is to see if modelToView
391 // is already allocated. If we don't do this check; sorting can become
392 // a performance bottleneck for applications where cells
393 // change rapidly in different parts of the table. If cells
394 // change alternately in the sorting column and then outside of
395 // it this class can end up re-sorting on alternate cell updates -
396 // which can be a performance problem for large tables. The last
397 // clause avoids this problem.
398 int column = e.getColumn();
399 if (e.getFirstRow() == e.getLastRow()
400 && column != TableModelEvent.ALL_COLUMNS
401 && getSortingStatus(column) == NOT_SORTED
402 && modelToView != null) {
403 int viewIndex = getModelToView()[e.getFirstRow()];
404 fireTableChanged(new TableModelEvent(TableSorter.this,
405 viewIndex, viewIndex,
406 column, e.getType()));
407 return;
408 }
409
410 // Something has happened to the data that may have invalidated the row order.
411 clearSortingState();
412 fireTableDataChanged();
413 }
414 }
415
416 private class MouseHandler extends MouseAdapter {
417 public void mouseClicked(MouseEvent e) {
418 JTableHeader h = (JTableHeader) e.getSource();
419 TableColumnModel columnModel = h.getColumnModel();
420 int viewColumn = columnModel.getColumnIndexAtX(e.getX());
421 int column = columnModel.getColumn(viewColumn).getModelIndex();
422 if (column != -1) {
423 int status = getSortingStatus(column);
424 if (!e.isControlDown()) {
425 cancelSorting();
426 }
427 // Cycle the sorting states through {NOT_SORTED, ASCENDING, DESCENDING} or
428 // {NOT_SORTED, DESCENDING, ASCENDING} depending on whether shift is pressed.
429 status = status + (e.isShiftDown() ? -1 : 1);
430 status = (status + 4) % 3 - 1; // signed mod, returning {-1, 0, 1}
431 setSortingStatus(column, status);
432 }
433 }
434 }
435
436 private static class Arrow implements Icon {
437 private final boolean descending;
438 private final int size;
439 private final int priority;
440
441 public Arrow(boolean descending, int size, int priority) {
442 this.descending = descending;
443 this.size = size;
444 this.priority = priority;
445 }
446
447 public void paintIcon(Component c, Graphics g, int x, int y) {
448 Color color = c == null ? Color.GRAY : c.getBackground();
449 // In a compound sort, make each succesive triangle 20%
450 // smaller than the previous one.
451 int dx = (int)(size/2*Math.pow(0.8, priority));
452 int dy = descending ? dx : -dx;
453 // Align icon (roughly) with font baseline.
454 y = y + 5*size/6 + (descending ? -dy : 0);
455 int shift = descending ? 1 : -1;
456 g.translate(x, y);
457
458 // Right diagonal.
459 g.setColor(color.darker());
460 g.drawLine(dx / 2, dy, 0, 0);
461 g.drawLine(dx / 2, dy + shift, 0, shift);
462
463 // Left diagonal.
464 g.setColor(color.brighter());
465 g.drawLine(dx / 2, dy, dx, 0);
466 g.drawLine(dx / 2, dy + shift, dx, shift);
467
468 // Horizontal line.
469 if (descending) {
470 g.setColor(color.darker().darker());
471 } else {
472 g.setColor(color.brighter().brighter());
473 }
474 g.drawLine(dx, 0, 0, 0);
475
476 g.setColor(color);
477 g.translate(-x, -y);
478 }
479
480 public int getIconWidth() {
481 return size;
482 }
483
484 public int getIconHeight() {
485 return size;
486 }
487
488 }
489 private class SortableHeaderRenderer implements TableCellRenderer {
490 private final TableCellRenderer tableCellRenderer;
491
492 public SortableHeaderRenderer(TableCellRenderer tableCellRenderer) {
493 this.tableCellRenderer = tableCellRenderer;
494 }
495
496 public Component getTableCellRendererComponent(JTable table,
497 Object value,
498 boolean isSelected,
499 boolean hasFocus,
500 int row,
501 int column) {
502 Component c = tableCellRenderer.getTableCellRendererComponent(table,
503 value, isSelected, hasFocus, row, column);
504 if (c instanceof JLabel) {
505 JLabel l = (JLabel) c;
506 l.setHorizontalAlignment(SwingConstants.LEADING);
507 l.setHorizontalTextPosition(JLabel.LEADING);
508 int modelColumn = table.convertColumnIndexToModel(column);
509 Icon icon = getHeaderRendererIcon(modelColumn, l.getFont().getSize());
510 l.setIcon(icon);
511 }
512 return c;
513 }
514 }
515
516 private static class Directive {
517 private final int column;
518 private final int direction;
519
520 public Directive(int column, int direction) {
521 this.column = column;
522 this.direction = direction;
523 }
524 }
525
526 private static Icon sortAscendingIcon = null;
527 private static Icon sortDescendingIcon = null;
528
529 static {
530 try {
531 sortAscendingIcon = IconUtils.getIcon(TableSorter.class, "images/sortAscending.png");
532 sortDescendingIcon = IconUtils.getIcon(TableSorter.class, "images/sortDescending.png");
533 } catch (Exception e) {
534 // do nothing
535 }
536
537 }
538
539 }