2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
23 import java.awt.Color;
24 import java.awt.Component;
25 import java.awt.Graphics;
26 import java.awt.event.MouseAdapter;
27 import java.awt.event.MouseEvent;
28 import java.awt.event.MouseListener;
29 import java.util.ArrayList;
30 import java.util.Arrays;
31 import java.util.Comparator;
32 import java.util.HashMap;
33 import java.util.Iterator;
34 import java.util.List;
37 import javax.swing.Icon;
38 import javax.swing.JLabel;
39 import javax.swing.JTable;
40 import javax.swing.event.TableModelEvent;
41 import javax.swing.event.TableModelListener;
42 import javax.swing.table.AbstractTableModel;
43 import javax.swing.table.JTableHeader;
44 import javax.swing.table.TableCellRenderer;
45 import javax.swing.table.TableColumnModel;
46 import javax.swing.table.TableModel;
49 * TableSorter is a decorator for TableModels; adding sorting functionality to a
50 * supplied TableModel. TableSorter does not store or copy the data in its
51 * TableModel; instead it maintains a map from the row indexes of the view to
52 * the row indexes of the model. As requests are made of the sorter (like
53 * getValueAt(row, col)) they are passed to the underlying model after the row
54 * numbers have been translated via the internal mapping array. This way, the
55 * TableSorter appears to hold another copy of the table with the rows in a
58 * TableSorter registers itself as a listener to the underlying model, just as
59 * the JTable itself would. Events recieved from the model are examined,
60 * sometimes manipulated (typically widened), and then passed on to the
61 * TableSorter's listeners (typically the JTable). If a change to the model has
62 * invalidated the order of TableSorter's rows, a note of this is made and the
63 * sorter will resort the rows the next time a value is requested.
65 * When the tableHeader property is set, either by using the setTableHeader()
66 * method or the two argument constructor, the table header may be used as a
67 * complete UI for TableSorter. The default renderer of the tableHeader is
68 * decorated with a renderer that indicates the sorting status of each column.
69 * In addition, a mouse listener is installed with the following behavior:
71 * <li>Mouse-click: Clears the sorting status of all other columns and advances
72 * the sorting status of that column through three values: {NOT_SORTED,
73 * ASCENDING, DESCENDING} (then back to NOT_SORTED again).
74 * <li>SHIFT-mouse-click: Clears the sorting status of all other columns and
75 * cycles the sorting status of the column through the same three values, in the
76 * opposite order: {NOT_SORTED, DESCENDING, ASCENDING}.
77 * <li>CONTROL-mouse-click and CONTROL-SHIFT-mouse-click: as above except that
78 * the changes to the column do not cancel the statuses of columns that are
79 * already sorting - giving a way to initiate a compound sort.
82 * This is a long overdue rewrite of a class of the same name that first
83 * appeared in the swing table demos in 1997.
85 * @author Philip Milne
86 * @author Brendon McLean
87 * @author Dan van Enckevort
88 * @author Parwinder Sekhon
89 * @version 2.0 02/27/04
92 public class TableSorter extends AbstractTableModel
94 protected TableModel tableModel;
96 public static final int DESCENDING = -1;
98 public static final int NOT_SORTED = 0;
100 public static final int ASCENDING = 1;
102 private static Directive EMPTY_DIRECTIVE = new Directive(-1, NOT_SORTED);
104 public static final Comparator COMPARABLE_COMAPRATOR = new Comparator()
106 public int compare(Object o1, Object o2)
108 return ((Comparable) o1).compareTo(o2);
112 public static final Comparator LEXICAL_COMPARATOR = new Comparator()
114 public int compare(Object o1, Object o2)
116 return o1.toString().compareTo(o2.toString());
120 private Row[] viewToModel;
122 private int[] modelToView;
124 private JTableHeader tableHeader;
126 private MouseListener mouseListener;
128 private TableModelListener tableModelListener;
130 private Map columnComparators = new HashMap();
132 private List sortingColumns = new ArrayList();
136 this.mouseListener = new MouseHandler();
137 this.tableModelListener = new TableModelHandler();
140 public TableSorter(TableModel tableModel)
143 setTableModel(tableModel);
146 public TableSorter(TableModel tableModel, JTableHeader tableHeader)
149 setTableHeader(tableHeader);
150 setTableModel(tableModel);
153 private void clearSortingState()
159 public TableModel getTableModel()
164 public void setTableModel(TableModel tableModel)
166 if (this.tableModel != null)
168 this.tableModel.removeTableModelListener(tableModelListener);
171 this.tableModel = tableModel;
172 if (this.tableModel != null)
174 this.tableModel.addTableModelListener(tableModelListener);
178 fireTableStructureChanged();
181 public JTableHeader getTableHeader()
186 public void setTableHeader(JTableHeader tableHeader)
188 if (this.tableHeader != null)
190 this.tableHeader.removeMouseListener(mouseListener);
191 TableCellRenderer defaultRenderer = this.tableHeader
192 .getDefaultRenderer();
193 if (defaultRenderer instanceof SortableHeaderRenderer)
196 .setDefaultRenderer(((SortableHeaderRenderer) defaultRenderer).tableCellRenderer);
199 this.tableHeader = tableHeader;
200 if (this.tableHeader != null)
202 this.tableHeader.addMouseListener(mouseListener);
203 this.tableHeader.setDefaultRenderer(new SortableHeaderRenderer(
204 this.tableHeader.getDefaultRenderer()));
208 public boolean isSorting()
210 return sortingColumns.size() != 0;
213 private Directive getDirective(int column)
215 for (int i = 0; i < sortingColumns.size(); i++)
217 Directive directive = (Directive) sortingColumns.get(i);
218 if (directive.column == column)
223 return EMPTY_DIRECTIVE;
226 public int getSortingStatus(int column)
228 return getDirective(column).direction;
231 private void sortingStatusChanged()
234 fireTableDataChanged();
235 if (tableHeader != null)
237 tableHeader.repaint();
241 public void setSortingStatus(int column, int status)
243 Directive directive = getDirective(column);
244 if (directive != EMPTY_DIRECTIVE)
246 sortingColumns.remove(directive);
248 if (status != NOT_SORTED)
250 sortingColumns.add(new Directive(column, status));
252 sortingStatusChanged();
255 protected Icon getHeaderRendererIcon(int column, int size)
257 Directive directive = getDirective(column);
258 if (directive == EMPTY_DIRECTIVE)
262 return new Arrow(directive.direction == DESCENDING, size,
263 sortingColumns.indexOf(directive));
266 private void cancelSorting()
268 sortingColumns.clear();
269 sortingStatusChanged();
272 public void setColumnComparator(Class type, Comparator comparator)
274 if (comparator == null)
276 columnComparators.remove(type);
280 columnComparators.put(type, comparator);
284 protected Comparator getComparator(int column)
286 Class columnType = tableModel.getColumnClass(column);
287 Comparator comparator = (Comparator) columnComparators.get(columnType);
288 if (comparator != null)
292 if (Comparable.class.isAssignableFrom(columnType))
294 return COMPARABLE_COMAPRATOR;
296 return LEXICAL_COMPARATOR;
299 private Row[] getViewToModel()
301 if (viewToModel == null)
303 int tableModelRowCount = tableModel.getRowCount();
304 viewToModel = new Row[tableModelRowCount];
305 for (int row = 0; row < tableModelRowCount; row++)
307 viewToModel[row] = new Row(row);
312 Arrays.sort(viewToModel);
318 public int modelIndex(int viewIndex)
320 return getViewToModel()[viewIndex].modelIndex;
323 private int[] getModelToView()
325 if (modelToView == null)
327 int n = getViewToModel().length;
328 modelToView = new int[n];
329 for (int i = 0; i < n; i++)
331 modelToView[modelIndex(i)] = i;
337 // TableModel interface methods
339 public int getRowCount()
341 return (tableModel == null) ? 0 : tableModel.getRowCount();
344 public int getColumnCount()
346 return (tableModel == null) ? 0 : tableModel.getColumnCount();
349 public String getColumnName(int column)
351 return tableModel.getColumnName(column);
354 public Class getColumnClass(int column)
356 return tableModel.getColumnClass(column);
359 public boolean isCellEditable(int row, int column)
361 return tableModel.isCellEditable(modelIndex(row), column);
364 public Object getValueAt(int row, int column)
366 return tableModel.getValueAt(modelIndex(row), column);
369 public void setValueAt(Object aValue, int row, int column)
371 tableModel.setValueAt(aValue, modelIndex(row), column);
376 private class Row implements Comparable
378 private int modelIndex;
380 public Row(int index)
382 this.modelIndex = index;
385 public int compareTo(Object o)
387 int row1 = modelIndex;
388 int row2 = ((Row) o).modelIndex;
390 for (Iterator it = sortingColumns.iterator(); it.hasNext();)
392 Directive directive = (Directive) it.next();
393 int column = directive.column;
394 Object o1 = tableModel.getValueAt(row1, column);
395 Object o2 = tableModel.getValueAt(row2, column);
398 // Define null less than everything, except null.
399 if (o1 == null && o2 == null)
413 comparison = getComparator(column).compare(o1, o2);
417 return directive.direction == DESCENDING ? -comparison
425 private class TableModelHandler implements TableModelListener
427 public void tableChanged(TableModelEvent e)
429 // If we're not sorting by anything, just pass the event along.
437 // If the table structure has changed, cancel the sorting; the
438 // sorting columns may have been either moved or deleted from
440 if (e.getFirstRow() == TableModelEvent.HEADER_ROW)
447 // We can map a cell event through to the view without widening
448 // when the following conditions apply:
450 // a) all the changes are on one row (e.getFirstRow() == e.getLastRow())
452 // b) all the changes are in one column (column !=
453 // TableModelEvent.ALL_COLUMNS) and,
454 // c) we are not sorting on that column (getSortingStatus(column) ==
456 // d) a reverse lookup will not trigger a sort (modelToView != null)
458 // Note: INSERT and DELETE events fail this test as they have column ==
461 // The last check, for (modelToView != null) is to see if modelToView
462 // is already allocated. If we don't do this check; sorting can become
463 // a performance bottleneck for applications where cells
464 // change rapidly in different parts of the table. If cells
465 // change alternately in the sorting column and then outside of
466 // it this class can end up re-sorting on alternate cell updates -
467 // which can be a performance problem for large tables. The last
468 // clause avoids this problem.
469 int column = e.getColumn();
470 if (e.getFirstRow() == e.getLastRow()
471 && column != TableModelEvent.ALL_COLUMNS
472 && getSortingStatus(column) == NOT_SORTED
473 && modelToView != null)
475 int viewIndex = getModelToView()[e.getFirstRow()];
476 fireTableChanged(new TableModelEvent(TableSorter.this, viewIndex,
477 viewIndex, column, e.getType()));
481 // Something has happened to the data that may have invalidated the row
484 fireTableDataChanged();
489 private class MouseHandler extends MouseAdapter
491 public void mouseClicked(MouseEvent e)
493 JTableHeader h = (JTableHeader) e.getSource();
494 TableColumnModel columnModel = h.getColumnModel();
495 int viewColumn = columnModel.getColumnIndexAtX(e.getX());
496 int column = columnModel.getColumn(viewColumn).getModelIndex();
499 int status = getSortingStatus(column);
500 if (!e.isControlDown())
504 // Cycle the sorting states through {NOT_SORTED, ASCENDING, DESCENDING}
506 // {NOT_SORTED, DESCENDING, ASCENDING} depending on whether shift is
508 status = status + (e.isShiftDown() ? -1 : 1);
509 status = (status + 4) % 3 - 1; // signed mod, returning {-1, 0, 1}
510 setSortingStatus(column, status);
515 private static class Arrow implements Icon
517 private boolean descending;
521 private int priority;
523 public Arrow(boolean descending, int size, int priority)
525 this.descending = descending;
527 this.priority = priority;
530 public void paintIcon(Component c, Graphics g, int x, int y)
532 Color color = c == null ? Color.GRAY : c.getBackground();
533 // In a compound sort, make each succesive triangle 20%
534 // smaller than the previous one.
535 int dx = (int) (size / 2 * Math.pow(0.8, priority));
536 int dy = descending ? dx : -dx;
537 // Align icon (roughly) with font baseline.
538 y = y + 5 * size / 6 + (descending ? -dy : 0);
539 int shift = descending ? 1 : -1;
543 g.setColor(color.darker());
544 g.drawLine(dx / 2, dy, 0, 0);
545 g.drawLine(dx / 2, dy + shift, 0, shift);
548 g.setColor(color.brighter());
549 g.drawLine(dx / 2, dy, dx, 0);
550 g.drawLine(dx / 2, dy + shift, dx, shift);
555 g.setColor(color.darker().darker());
559 g.setColor(color.brighter().brighter());
561 g.drawLine(dx, 0, 0, 0);
567 public int getIconWidth()
572 public int getIconHeight()
578 private class SortableHeaderRenderer implements TableCellRenderer
580 private TableCellRenderer tableCellRenderer;
582 public SortableHeaderRenderer(TableCellRenderer tableCellRenderer)
584 this.tableCellRenderer = tableCellRenderer;
587 public Component getTableCellRendererComponent(JTable table,
588 Object value, boolean isSelected, boolean hasFocus, int row,
591 Component c = tableCellRenderer.getTableCellRendererComponent(table,
592 value, isSelected, hasFocus, row, column);
593 if (c instanceof JLabel)
595 JLabel l = (JLabel) c;
596 l.setHorizontalTextPosition(JLabel.LEFT);
597 int modelColumn = table.convertColumnIndexToModel(column);
598 l.setIcon(getHeaderRendererIcon(modelColumn, l.getFont().getSize()));
604 private static class Directive
608 private int direction;
610 public Directive(int column, int direction)
612 this.column = column;
613 this.direction = direction;