KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > hsqldb > util > TableSorter


1 package org.hsqldb.util;
2
3 import java.util.ArrayList JavaDoc;
4 import java.util.Arrays JavaDoc;
5 import java.util.Comparator JavaDoc;
6 import java.util.HashMap JavaDoc;
7 import java.util.Iterator JavaDoc;
8 import java.util.List JavaDoc;
9 import java.util.Map JavaDoc;
10 import java.awt.Color JavaDoc;
11 import java.awt.Component JavaDoc;
12 import java.awt.Graphics JavaDoc;
13 import java.awt.event.MouseAdapter JavaDoc;
14 import java.awt.event.MouseEvent JavaDoc;
15 import java.awt.event.MouseListener JavaDoc;
16
17 import javax.swing.Icon JavaDoc;
18 import javax.swing.JLabel JavaDoc;
19 import javax.swing.JTable JavaDoc;
20 import javax.swing.event.TableModelEvent JavaDoc;
21 import javax.swing.event.TableModelListener JavaDoc;
22 import javax.swing.table.AbstractTableModel JavaDoc;
23 import javax.swing.table.JTableHeader JavaDoc;
24 import javax.swing.table.TableCellRenderer JavaDoc;
25 import javax.swing.table.TableColumnModel JavaDoc;
26 import javax.swing.table.TableModel JavaDoc;
27
28 /**
29  * TableSorter is a decorator for TableModels; adding sorting
30  * functionality to a supplied TableModel. TableSorter does
31  * not store or copy the data in its TableModel; instead it maintains
32  * a map from the row indexes of the view to the row indexes of the
33  * model. As requests are made of the sorter (like getValueAt(row, col))
34  * they are passed to the underlying model after the row numbers
35  * have been translated via the internal mapping array. This way,
36  * the TableSorter appears to hold another copy of the table
37  * with the rows in a different order.
38  * <p/>
39  * TableSorter registers itself as a listener to the underlying model,
40  * just as the JTable itself would. Events recieved from the model
41  * are examined, sometimes manipulated (typically widened), and then
42  * passed on to the TableSorter's listeners (typically the JTable).
43  * If a change to the model has invalidated the order of TableSorter's
44  * rows, a note of this is made and the sorter will resort the
45  * rows the next time a value is requested.
46  * <p/>
47  * When the tableHeader property is set, either by using the
48  * setTableHeader() method or the two argument constructor, the
49  * table header may be used as a complete UI for TableSorter.
50  * The default renderer of the tableHeader is decorated with a renderer
51  * that indicates the sorting status of each column. In addition,
52  * a mouse listener is installed with the following behavior:
53  * <ul>
54  * <li>
55  * Mouse-click: Clears the sorting status of all other columns
56  * and advances the sorting status of that column through three
57  * values: {NOT_SORTED, ASCENDING, DESCENDING} (then back to
58  * NOT_SORTED again).
59  * <li>
60  * SHIFT-mouse-click: Clears the sorting status of all other columns
61  * and cycles the sorting status of the column through the same
62  * three values, in the opposite order: {NOT_SORTED, DESCENDING, ASCENDING}.
63  * <li>
64  * CONTROL-mouse-click and CONTROL-SHIFT-mouse-click: as above except
65  * that the changes to the column do not cancel the statuses of columns
66  * that are already sorting - giving a way to initiate a compound
67  * sort.
68  * </ul>
69  * <p/>
70  * This is a long overdue rewrite of a class of the same name that
71  * first appeared in the swing table demos in 1997.
72  *
73  * @author Philip Milne
74  * @author Brendon McLean
75  * @author Dan van Enckevort
76  * @author Parwinder Sekhon
77  * @version 2.0 02/27/04
78  */

79 public class TableSorter extends AbstractTableModel JavaDoc {
80
81     protected TableModel JavaDoc tableModel;
82     public static final int DESCENDING = -1;
83     public static final int NOT_SORTED = 0;
84     public static final int ASCENDING = 1;
85     private static Directive EMPTY_DIRECTIVE = new Directive(-1, NOT_SORTED);
86     public static final Comparator JavaDoc COMPARABLE_COMPARATOR = new Comparator JavaDoc() {
87
88         public int compare(Object JavaDoc o1, Object JavaDoc o2) {
89
90             if (o1 == o2) {
91                 return 0;
92             }
93
94             if (o1 == null) {
95                 if (o2 == null) {
96                     return 0;
97                 }
98
99                 return -1;
100             }
101
102             if (o2 == null) {
103                 return 1;
104             }
105
106             return ((Comparable JavaDoc) o1).compareTo(o2);
107         }
108     };
109     public static final Comparator JavaDoc LEXICAL_COMPARATOR = new Comparator JavaDoc() {
110
111         public int compare(Object JavaDoc o1, Object JavaDoc o2) {
112             return o1.toString().compareTo(o2.toString());
113         }
114     };
115     private Row[] viewToModel;
116     private int[] modelToView;
117     private JTableHeader JavaDoc tableHeader;
118     private MouseListener JavaDoc mouseListener;
119     private TableModelListener JavaDoc tableModelListener;
120     private Map JavaDoc columnComparators = new HashMap JavaDoc();
121     private List JavaDoc sortingColumns = new ArrayList JavaDoc();
122
123     public TableSorter() {
124         this.mouseListener = new MouseHandler();
125         this.tableModelListener = new TableModelHandler();
126     }
127
128     public TableSorter(TableModel JavaDoc tableModel) {
129
130         this();
131
132         setTableModel(tableModel);
133     }
134
135     public TableSorter(TableModel JavaDoc tableModel, JTableHeader JavaDoc tableHeader) {
136
137         this();
138
139         setTableHeader(tableHeader);
140         setTableModel(tableModel);
141     }
142
143     private void clearSortingState() {
144         viewToModel = null;
145         modelToView = null;
146     }
147
148     public TableModel JavaDoc getTableModel() {
149         return tableModel;
150     }
151
152     public void setTableModel(TableModel JavaDoc tableModel) {
153
154         if (this.tableModel != null) {
155             this.tableModel.removeTableModelListener(tableModelListener);
156         }
157
158         this.tableModel = tableModel;
159
160         if (this.tableModel != null) {
161             this.tableModel.addTableModelListener(tableModelListener);
162         }
163
164         clearSortingState();
165         fireTableStructureChanged();
166     }
167
168     public JTableHeader JavaDoc getTableHeader() {
169         return tableHeader;
170     }
171
172     public void setTableHeader(JTableHeader JavaDoc tableHeader) {
173
174         if (this.tableHeader != null) {
175             this.tableHeader.removeMouseListener(mouseListener);
176
177             TableCellRenderer JavaDoc defaultRenderer =
178                 this.tableHeader.getDefaultRenderer();
179
180             if (defaultRenderer instanceof SortableHeaderRenderer) {
181                 this.tableHeader.setDefaultRenderer(
182                     ((SortableHeaderRenderer) defaultRenderer)
183                         .tableCellRenderer);
184             }
185         }
186
187         this.tableHeader = tableHeader;
188
189         if (this.tableHeader != null) {
190             this.tableHeader.addMouseListener(mouseListener);
191             this.tableHeader.setDefaultRenderer(
192                 new SortableHeaderRenderer(
193                     this.tableHeader.getDefaultRenderer()));
194         }
195     }
196
197     public boolean isSorting() {
198         return sortingColumns.size() != 0;
199     }
200
201     private Directive getDirective(int column) {
202
203         for (int i = 0; i < sortingColumns.size(); i++) {
204             Directive directive = (Directive) sortingColumns.get(i);
205
206             if (directive.column == column) {
207                 return directive;
208             }
209         }
210
211         return EMPTY_DIRECTIVE;
212     }
213
214     public int getSortingStatus(int column) {
215         return getDirective(column).direction;
216     }
217
218     private void sortingStatusChanged() {
219
220         clearSortingState();
221         fireTableDataChanged();
222
223         if (tableHeader != null) {
224             tableHeader.repaint();
225         }
226     }
227
228     public void setSortingStatus(int column, int status) {
229
230         Directive directive = getDirective(column);
231
232         if (directive != EMPTY_DIRECTIVE) {
233             sortingColumns.remove(directive);
234         }
235
236         if (status != NOT_SORTED) {
237             sortingColumns.add(new Directive(column, status));
238         }
239
240         sortingStatusChanged();
241     }
242
243     protected Icon JavaDoc getHeaderRendererIcon(int column, int size) {
244
245         Directive directive = getDirective(column);
246
247         if (directive == EMPTY_DIRECTIVE) {
248             return null;
249         }
250
251         return new Arrow(directive.direction == DESCENDING, size,
252                          sortingColumns.indexOf(directive));
253     }
254
255     private void cancelSorting() {
256         sortingColumns.clear();
257         sortingStatusChanged();
258     }
259
260     public void setColumnComparator(Class JavaDoc type, Comparator JavaDoc comparator) {
261
262         if (comparator == null) {
263             columnComparators.remove(type);
264         } else {
265             columnComparators.put(type, comparator);
266         }
267     }
268
269     protected Comparator JavaDoc getComparator(int column) {
270
271         Class JavaDoc columnType = tableModel.getColumnClass(column);
272         Comparator JavaDoc comparator =
273             (Comparator JavaDoc) columnComparators.get(columnType);
274
275         if (comparator != null) {
276             return comparator;
277         }
278
279         if (Comparable JavaDoc.class.isAssignableFrom(columnType)) {
280             return COMPARABLE_COMPARATOR;
281         }
282
283         return LEXICAL_COMPARATOR;
284     }
285
286     private Row[] getViewToModel() {
287
288         if (viewToModel == null) {
289             int tableModelRowCount = tableModel.getRowCount();
290
291             viewToModel = new Row[tableModelRowCount];
292
293             for (int row = 0; row < tableModelRowCount; row++) {
294                 viewToModel[row] = new Row(row);
295             }
296
297             if (isSorting()) {
298                 Arrays.sort(viewToModel);
299             }
300         }
301
302         return viewToModel;
303     }
304
305     public int modelIndex(int viewIndex) {
306         return getViewToModel()[viewIndex].modelIndex;
307     }
308
309     private int[] getModelToView() {
310
311         if (modelToView == null) {
312             int n = getViewToModel().length;
313
314             modelToView = new int[n];
315
316             for (int i = 0; i < n; i++) {
317                 modelToView[modelIndex(i)] = i;
318             }
319         }
320
321         return modelToView;
322     }
323
324     // TableModel interface methods
325
public int getRowCount() {
326         return (tableModel == null) ? 0
327                                     : tableModel.getRowCount();
328     }
329
330     public int getColumnCount() {
331         return (tableModel == null) ? 0
332                                     : tableModel.getColumnCount();
333     }
334
335     public String JavaDoc getColumnName(int column) {
336         return tableModel.getColumnName(column);
337     }
338
339     public Class JavaDoc getColumnClass(int column) {
340         return tableModel.getColumnClass(column);
341     }
342
343     public boolean isCellEditable(int row, int column) {
344         return tableModel.isCellEditable(modelIndex(row), column);
345     }
346
347     public Object JavaDoc getValueAt(int row, int column) {
348         return tableModel.getValueAt(modelIndex(row), column);
349     }
350
351     public void setValueAt(Object JavaDoc aValue, int row, int column) {
352         tableModel.setValueAt(aValue, modelIndex(row), column);
353     }
354
355     // Helper classes
356
private class Row implements Comparable JavaDoc {
357
358         private int modelIndex;
359
360         public Row(int index) {
361             this.modelIndex = index;
362         }
363
364         public int compareTo(Object JavaDoc o) {
365
366             int row1 = modelIndex;
367             int row2 = ((Row) o).modelIndex;
368
369             for (Iterator JavaDoc it = sortingColumns.iterator(); it.hasNext(); ) {
370                 Directive directive = (Directive) it.next();
371                 int column = directive.column;
372                 Object JavaDoc o1 = tableModel.getValueAt(row1, column);
373                 Object JavaDoc o2 = tableModel.getValueAt(row2, column);
374                 int comparison = 0;
375
376                 // Define null less than everything, except null.
377
if (o1 == null && o2 == null) {
378                     comparison = 0;
379                 } else if (o1 == null) {
380                     comparison = -1;
381                 } else if (o2 == null) {
382                     comparison = 1;
383                 } else {
384                     comparison = getComparator(column).compare(o1, o2);
385                 }
386
387                 if (comparison != 0) {
388                     return directive.direction == DESCENDING ? -comparison
389                                                              : comparison;
390                 }
391             }
392
393             return 0;
394         }
395     }
396
397     private class TableModelHandler implements TableModelListener JavaDoc {
398
399         public void tableChanged(TableModelEvent JavaDoc e) {
400
401             // If we're not sorting by anything, just pass the event along.
402
if (!isSorting()) {
403                 clearSortingState();
404                 fireTableChanged(e);
405
406                 return;
407             }
408
409             // If the table structure has changed, cancel the sorting; the
410
// sorting columns may have been either moved or deleted from
411
// the model.
412
if (e == null || e.getFirstRow() == TableModelEvent.HEADER_ROW) {
413                 cancelSorting();
414                 fireTableChanged(e);
415
416                 return;
417             }
418
419             // We can map a cell event through to the view without widening
420
// when the following conditions apply:
421
//
422
// a) all the changes are on one row (e.getFirstRow() == e.getLastRow()) and,
423
// b) all the changes are in one column (column != TableModelEvent.ALL_COLUMNS) and,
424
// c) we are not sorting on that column (getSortingStatus(column) == NOT_SORTED) and,
425
// d) a reverse lookup will not trigger a sort (modelToView != null)
426
//
427
// Note: INSERT and DELETE events fail this test as they have column == ALL_COLUMNS.
428
//
429
// The last check, for (modelToView != null) is to see if modelToView
430
// is already allocated. If we don't do this check; sorting can become
431
// a performance bottleneck for applications where cells
432
// change rapidly in different parts of the table. If cells
433
// change alternately in the sorting column and then outside of
434
// it this class can end up re-sorting on alternate cell updates -
435
// which can be a performance problem for large tables. The last
436
// clause avoids this problem.
437
int column = e.getColumn();
438
439             if (e.getFirstRow() == e.getLastRow()
440                     && column != TableModelEvent.ALL_COLUMNS
441                     && getSortingStatus(column) == NOT_SORTED
442                     && modelToView != null) {
443                 int viewIndex = getModelToView()[e.getFirstRow()];
444
445                 fireTableChanged(new TableModelEvent JavaDoc(TableSorter.this,
446                                                      viewIndex, viewIndex,
447                                                      column, e.getType()));
448
449                 return;
450             }
451
452             // Something has happened to the data that may have invalidated the row order.
453
clearSortingState();
454             fireTableDataChanged();
455
456             return;
457         }
458     }
459
460     private class MouseHandler extends MouseAdapter JavaDoc {
461
462         public void mouseClicked(MouseEvent JavaDoc e) {
463
464             JTableHeader JavaDoc h = (JTableHeader JavaDoc) e.getSource();
465             TableColumnModel JavaDoc columnModel = h.getColumnModel();
466             int viewColumn = columnModel.getColumnIndexAtX(e.getX());
467             int column = columnModel.getColumn(viewColumn).getModelIndex();
468
469             if (column != -1) {
470                 int status = getSortingStatus(column);
471
472                 if (!e.isControlDown()) {
473                     cancelSorting();
474                 }
475
476                 // Cycle the sorting states through {NOT_SORTED, ASCENDING, DESCENDING} or
477
// {NOT_SORTED, DESCENDING, ASCENDING} depending on whether shift is pressed.
478
status = status + (e.isShiftDown() ? -1
479                                                    : 1);
480                 status = (status + 4) % 3 - 1; // signed mod, returning {-1, 0, 1}
481

482                 setSortingStatus(column, status);
483             }
484         }
485     }
486
487     private static class Arrow implements Icon JavaDoc {
488
489         private boolean descending;
490         private int size;
491         private int priority;
492
493         public Arrow(boolean descending, int size, int priority) {
494
495             this.descending = descending;
496             this.size = size;
497             this.priority = priority;
498         }
499
500         public void paintIcon(Component JavaDoc c, Graphics JavaDoc g, int x, int y) {
501
502             Color JavaDoc color = c == null ? Color.gray
503                                     : c.getBackground();
504
505             // In a compound sort, make each succesive triangle 20%
506
// smaller than the previous one.
507
int dx = (int) (size / 2 * Math.pow(0.8, priority));
508             int dy = descending ? dx
509                                 : -dx;
510
511             // Align icon (roughly) with font baseline.
512
y = y + 5 * size / 6 + (descending ? -dy
513                                                : 0);
514
515             int shift = descending ? 1
516                                    : -1;
517
518             g.translate(x, y);
519
520             // Right diagonal.
521
g.setColor(color.darker());
522             g.drawLine(dx / 2, dy, 0, 0);
523             g.drawLine(dx / 2, dy + shift, 0, shift);
524
525             // Left diagonal.
526
g.setColor(color.brighter());
527             g.drawLine(dx / 2, dy, dx, 0);
528             g.drawLine(dx / 2, dy + shift, dx, shift);
529
530             // Horizontal line.
531
if (descending) {
532                 g.setColor(color.darker().darker());
533             } else {
534                 g.setColor(color.brighter().brighter());
535             }
536
537             g.drawLine(dx, 0, 0, 0);
538             g.setColor(color);
539             g.translate(-x, -y);
540         }
541
542         public int getIconWidth() {
543             return size;
544         }
545
546         public int getIconHeight() {
547             return size;
548         }
549     }
550
551     private class SortableHeaderRenderer implements TableCellRenderer JavaDoc {
552
553         private TableCellRenderer JavaDoc tableCellRenderer;
554
555         public SortableHeaderRenderer(TableCellRenderer JavaDoc tableCellRenderer) {
556             this.tableCellRenderer = tableCellRenderer;
557         }
558
559         public Component JavaDoc getTableCellRendererComponent(JTable JavaDoc table,
560                 Object JavaDoc value, boolean isSelected, boolean hasFocus, int row,
561                 int column) {
562
563             Component JavaDoc c =
564                 tableCellRenderer.getTableCellRendererComponent(table, value,
565                     isSelected, hasFocus, row, column);
566
567             if (c instanceof JLabel JavaDoc) {
568                 JLabel JavaDoc l = (JLabel JavaDoc) c;
569
570                 l.setHorizontalTextPosition(JLabel.LEFT);
571
572                 int modelColumn = table.convertColumnIndexToModel(column);
573
574                 l.setIcon(getHeaderRendererIcon(modelColumn,
575                                                 l.getFont().getSize()));
576             }
577
578             return c;
579         }
580     }
581
582     private static class Directive {
583
584         private int column;
585         private int direction;
586
587         public Directive(int column, int direction) {
588             this.column = column;
589             this.direction = direction;
590         }
591     }
592 }
593
Popular Tags