Coverage details for ui.table.TableSorter

LineHitsSource
1 /*******************************************************************************
2  * InternetCafe is a software solution that helps the management of Cybercafes
3  * according with the ITALIAN DECREE LAW ON ANTI-TERROR MEASURES, 27 JULY 2005.
4  * Copyright (C) 2006 Guido Angelo Ingenito
5  
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version.
10  
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19  *******************************************************************************/
20 package ui.table;
21  
22 import java.awt.Color;
23 import java.awt.Component;
24 import java.awt.Graphics;
25 import java.awt.event.MouseAdapter;
26 import java.awt.event.MouseEvent;
27 import java.awt.event.MouseListener;
28 import java.util.ArrayList;
29 import java.util.Arrays;
30 import java.util.Comparator;
31 import java.util.HashMap;
32 import java.util.Iterator;
33 import java.util.List;
34 import java.util.Map;
35  
36 import javax.swing.Icon;
37 import javax.swing.JLabel;
38 import javax.swing.JTable;
39 import javax.swing.event.TableModelEvent;
40 import javax.swing.event.TableModelListener;
41 import javax.swing.table.AbstractTableModel;
42 import javax.swing.table.JTableHeader;
43 import javax.swing.table.TableCellRenderer;
44 import javax.swing.table.TableColumnModel;
45 import javax.swing.table.TableModel;
46  
47 /**
48  * TableSorter is a decorator for TableModels; adding sorting functionality to a
49  * supplied TableModel. TableSorter does not store or copy the data in its
50  * TableModel; instead it maintains a map from the row indexes of the view to
51  * the row indexes of the model. As requests are made of the sorter (like
52  * getValueAt(row, col)) they are passed to the underlying model after the row
53  * numbers have been translated via the internal mapping array. This way, the
54  * TableSorter appears to hold another copy of the table with the rows in a
55  * different order. <p/> TableSorter registers itself as a listener to the
56  * underlying model, just as the JTable itself would. Events recieved from the
57  * model are examined, sometimes manipulated (typically widened), and then
58  * passed on to the TableSorter's listeners (typically the JTable). If a change
59  * to the model has invalidated the order of TableSorter's rows, a note of this
60  * is made and the sorter will resort the rows the next time a value is
61  * requested. <p/> When the tableHeader property is set, either by using the
62  * setTableHeader() method or the two argument constructor, the table header may
63  * be used as a complete UI for TableSorter. The default renderer of the
64  * tableHeader is decorated with a renderer that indicates the sorting status of
65  * each column. In addition, a mouse listener is installed with the following
66  * behavior:
67  * <ul>
68  * <li> Mouse-click: Clears the sorting status of all other columns and advances
69  * the sorting status of that column through three values: {NOT_SORTED,
70  * ASCENDING, DESCENDING} (then back to NOT_SORTED again).
71  * <li> SHIFT-mouse-click: Clears the sorting status of all other columns and
72  * cycles the sorting status of the column through the same three values, in the
73  * opposite order: {NOT_SORTED, DESCENDING, ASCENDING}.
74  * <li> CONTROL-mouse-click and CONTROL-SHIFT-mouse-click: as above except that
75  * the changes to the column do not cancel the statuses of columns that are
76  * already sorting - giving a way to initiate a compound sort.
77  * </ul>
78  * <p/> This is a long overdue rewrite of a class of the same name that first
79  * appeared in the swing table demos in 1997.
80  *
81  * @author Philip Milne
82  * @author Brendon McLean
83  * @author Dan van Enckevort
84  * @author Parwinder Sekhon
85  * @version 2.0 02/27/04
86  */
87  
88 @SuppressWarnings("serial") //$NON-NLS-1$
890public class TableSorter extends AbstractTableModel {
90     protected TableModel tableModel;
91  
92     public static final int DESCENDING = -1;
93  
94     public static final int NOT_SORTED = 0;
95  
96     public static final int ASCENDING = 1;
97  
980    private static Directive EMPTY_DIRECTIVE = new Directive(-1, NOT_SORTED);
99  
100     @SuppressWarnings("unchecked") //$NON-NLS-1$
1010    public static final Comparator<Object> COMPARABLE_COMAPRATOR = new Comparator() {
102         public int compare(Object o1, Object o2) {
103             return ((Comparable<Object>) o1).compareTo(o2);
104         }
105     };
106  
107     @SuppressWarnings("unchecked") //$NON-NLS-1$
1080    public static final Comparator<Object> LEXICAL_COMPARATOR = new Comparator() {
109         public int compare(Object o1, Object o2) {
110             return o1.toString().compareTo(o2.toString());
111         }
112     };
113  
114     private Row[] viewToModel;
115  
1160    private int[] modelToView;
117  
118     private JTableHeader tableHeader;
119  
120     private MouseListener mouseListener;
121  
122     private TableModelListener tableModelListener;
123  
1240    private Map<Class, Comparator> columnComparators = new HashMap<Class, Comparator>();
125  
1260    private List<Directive> sortingColumns = new ArrayList<Directive>();
127  
1280    public TableSorter() {
1290        this.mouseListener = new MouseHandler();
1300        this.tableModelListener = new TableModelHandler();
1310    }
132  
133     public TableSorter(TableModel tableModel) {
1340        this();
1350        setTableModel(tableModel);
1360    }
137  
138     public TableSorter(TableModel tableModel, JTableHeader tableHeader) {
1390        this();
1400        setTableHeader(tableHeader);
1410        setTableModel(tableModel);
1420    }
143  
1440    private void clearSortingState() {
1450        viewToModel = null;
1460        modelToView = null;
1470    }
148  
149     public TableModel getTableModel() {
1500        return tableModel;
151     }
152  
153     public void setTableModel(TableModel tableModel) {
1540        if (this.tableModel != null) {
1550            this.tableModel.removeTableModelListener(tableModelListener);
156         }
157  
1580        this.tableModel = tableModel;
1590        if (this.tableModel != null) {
1600            this.tableModel.addTableModelListener(tableModelListener);
161         }
162  
1630        clearSortingState();
1640        fireTableStructureChanged();
1650    }
166  
167     public JTableHeader getTableHeader() {
1680        return tableHeader;
169     }
170  
171     public void setTableHeader(JTableHeader tableHeader) {
1720        if (this.tableHeader != null) {
1730            this.tableHeader.removeMouseListener(mouseListener);
1740            TableCellRenderer defaultRenderer = this.tableHeader
1750                    .getDefaultRenderer();
1760            if (defaultRenderer instanceof SortableHeaderRenderer) {
1770                this.tableHeader
1780                        .setDefaultRenderer(((SortableHeaderRenderer) defaultRenderer).tableCellRenderer);
179             }
180         }
1810        this.tableHeader = tableHeader;
1820        if (this.tableHeader != null) {
1830            this.tableHeader.addMouseListener(mouseListener);
1840            this.tableHeader.setDefaultRenderer(new SortableHeaderRenderer(
1850                    this.tableHeader.getDefaultRenderer()));
186         }
1870    }
188  
189     public boolean isSorting() {
1900        return sortingColumns.size() != 0;
191     }
192  
193     private Directive getDirective(int column) {
1940        for (int i = 0; i < sortingColumns.size(); i++) {
1950            Directive directive = sortingColumns.get(i);
1960            if (directive.column == column) {
1970                return directive;
198             }
199         }
2000        return EMPTY_DIRECTIVE;
201     }
202  
203     public int getSortingStatus(int column) {
2040        return getDirective(column).direction;
205     }
206  
207     private void sortingStatusChanged() {
2080        clearSortingState();
2090        fireTableDataChanged();
2100        if (tableHeader != null) {
2110            tableHeader.repaint();
212         }
2130    }
214  
215     @SuppressWarnings("unchecked") //$NON-NLS-1$
216     public void setSortingStatus(int column, int status) {
2170        Directive directive = getDirective(column);
2180        if (directive != EMPTY_DIRECTIVE) {
2190            sortingColumns.remove(directive);
220         }
2210        if (status != NOT_SORTED) {
2220            sortingColumns.add(new Directive(column, status));
223         }
2240        sortingStatusChanged();
2250    }
226  
227     protected Icon getHeaderRendererIcon(int column, int size) {
2280        Directive directive = getDirective(column);
2290        if (directive == EMPTY_DIRECTIVE) {
2300            return null;
231         }
2320        return new Arrow(directive.direction == DESCENDING, size,
2330                sortingColumns.indexOf(directive));
234     }
235  
2360    private void cancelSorting() {
2370        sortingColumns.clear();
2380        sortingStatusChanged();
2390    }
240  
241     @SuppressWarnings("unchecked") //$NON-NLS-1$
242     public void setColumnComparator(Class type, Comparator comparator) {
2430        if (comparator == null) {
2440            columnComparators.remove(type);
2450        } else {
2460            columnComparators.put(type, comparator);
247         }
2480    }
249  
250     @SuppressWarnings("unchecked") //$NON-NLS-1$
251     protected Comparator<Object> getComparator(int column) {
2520        Class columnType = tableModel.getColumnClass(column);
2530        Comparator<Object> comparator = columnComparators.get(columnType);
2540        if (comparator != null) {
2550            return comparator;
256         }
2570        if (Comparable.class.isAssignableFrom(columnType)) {
2580            return COMPARABLE_COMAPRATOR;
259         }
2600        return LEXICAL_COMPARATOR;
261     }
262  
263     private Row[] getViewToModel() {
2640        if (viewToModel == null) {
2650            int tableModelRowCount = tableModel.getRowCount();
2660            viewToModel = new Row[tableModelRowCount];
2670            for (int row = 0; row < tableModelRowCount; row++) {
2680                viewToModel[row] = new Row(row);
269             }
270  
2710            if (isSorting()) {
2720                Arrays.sort(viewToModel);
273             }
274         }
2750        return viewToModel;
276     }
277  
278     public int modelIndex(int viewIndex) {
2790        return getViewToModel()[viewIndex].modelIndex;
280     }
281  
2820    private int[] getModelToView() {
2830        if (modelToView == null) {
2840            int n = getViewToModel().length;
2850            modelToView = new int[n];
2860            for (int i = 0; i < n; i++) {
2870                modelToView[modelIndex(i)] = i;
288             }
289         }
2900        return modelToView;
291     }
292  
293     // TableModel interface methods
294  
295     public int getRowCount() {
2960        return (tableModel == null) ? 0 : tableModel.getRowCount();
297     }
298  
299     public int getColumnCount() {
3000        return (tableModel == null) ? 0 : tableModel.getColumnCount();
301     }
302  
303     public String getColumnName(int column) {
3040        return tableModel.getColumnName(column);
305     }
306  
307     @SuppressWarnings("unchecked") //$NON-NLS-1$
308     public Class getColumnClass(int column) {
3090        return tableModel.getColumnClass(column);
310     }
311  
312     public boolean isCellEditable(int row, int column) {
3130        return tableModel.isCellEditable(modelIndex(row), column);
314     }
315  
316     public Object getValueAt(int row, int column) {
3170        return tableModel.getValueAt(modelIndex(row), column);
318     }
319  
320     public void setValueAt(Object aValue, int row, int column) {
3210        tableModel.setValueAt(aValue, modelIndex(row), column);
3220    }
323  
324     // Helper classes
325  
326     private class Row implements Comparable {
327         private int modelIndex;
328  
329         public Row(int index) {
330             this.modelIndex = index;
331         }
332  
333         @SuppressWarnings("unchecked") //$NON-NLS-1$
334         public int compareTo(Object o) {
335             int row1 = modelIndex;
336             int row2 = ((Row) o).modelIndex;
337  
338             for (Iterator<Directive> it = sortingColumns.iterator(); it
339                     .hasNext();) {
340                 Directive directive = it.next();
341                 int column = directive.column;
342                 Object o1 = tableModel.getValueAt(row1, column);
343                 Object o2 = tableModel.getValueAt(row2, column);
344  
345                 int comparison = 0;
346                 // Define null less than everything, except null.
347                 if (o1 == null && o2 == null) {
348                     comparison = 0;
349                 } else if (o1 == null) {
350                     comparison = -1;
351                 } else if (o2 == null) {
352                     comparison = 1;
353                 } else {
354                     comparison = getComparator(column).compare(o1, o2);
355                 }
356                 if (comparison != 0) {
357                     return directive.direction == DESCENDING ? -comparison
358                             : comparison;
359                 }
360             }
361             return 0;
362         }
363     }
364  
365     private class TableModelHandler implements TableModelListener {
366         public void tableChanged(TableModelEvent e) {
367             // If we're not sorting by anything, just pass the event along.
368             if (!isSorting()) {
369                 clearSortingState();
370                 fireTableChanged(e);
371                 return;
372             }
373  
374             // If the table structure has changed, cancel the sorting; the
375             // sorting columns may have been either moved or deleted from
376             // the model.
377             if (e.getFirstRow() == TableModelEvent.HEADER_ROW) {
378                 cancelSorting();
379                 fireTableChanged(e);
380                 return;
381             }
382  
383             // We can map a cell event through to the view without widening
384             // when the following conditions apply:
385             //
386             // a) all the changes are on one row (e.getFirstRow() ==
387             // e.getLastRow()) and,
388             // b) all the changes are in one column (column !=
389             // TableModelEvent.ALL_COLUMNS) and,
390             // c) we are not sorting on that column (getSortingStatus(column) ==
391             // NOT_SORTED) and,
392             // d) a reverse lookup will not trigger a sort (modelToView != null)
393             //
394             // Note: INSERT and DELETE events fail this test as they have column
395             // == ALL_COLUMNS.
396             //
397             // The last check, for (modelToView != null) is to see if
398             // modelToView
399             // is already allocated. If we don't do this check; sorting can
400             // become
401             // a performance bottleneck for applications where cells
402             // change rapidly in different parts of the table. If cells
403             // change alternately in the sorting column and then outside of
404             // it this class can end up re-sorting on alternate cell updates -
405             // which can be a performance problem for large tables. The last
406             // clause avoids this problem.
407             int column = e.getColumn();
408             if (e.getFirstRow() == e.getLastRow()
409                     && column != TableModelEvent.ALL_COLUMNS
410                     && getSortingStatus(column) == NOT_SORTED
411                     && modelToView != null) {
412                 int viewIndex = getModelToView()[e.getFirstRow()];
413                 fireTableChanged(new TableModelEvent(TableSorter.this,
414                         viewIndex, viewIndex, column, e.getType()));
415                 return;
416             }
417  
418             // Something has happened to the data that may have invalidated the
419             // row order.
420             clearSortingState();
421             fireTableDataChanged();
422             return;
423         }
424     }
425  
426     private class MouseHandler extends MouseAdapter {
427         public void mouseClicked(MouseEvent e) {
428             JTableHeader h = (JTableHeader) e.getSource();
429             TableColumnModel columnModel = h.getColumnModel();
430             int viewColumn = columnModel.getColumnIndexAtX(e.getX());
431             int column = columnModel.getColumn(viewColumn).getModelIndex();
432             if (column != -1) {
433                 int status = getSortingStatus(column);
434                 if (!e.isControlDown()) {
435                     cancelSorting();
436                 }
437                 // Cycle the sorting states through {NOT_SORTED, ASCENDING,
438                 // DESCENDING} or
439                 // {NOT_SORTED, DESCENDING, ASCENDING} depending on whether
440                 // shift is pressed.
441                 status = status + (e.isShiftDown() ? -1 : 1);
442                 status = (status + 4) % 3 - 1; // signed mod, returning {-1, 0,
443                 // 1}
444                 setSortingStatus(column, status);
445             }
446         }
447     }
448  
449     private static class Arrow implements Icon {
450         private boolean descending;
451  
452         private int size;
453  
454         private int priority;
455  
456         public Arrow(boolean descending, int size, int priority) {
457             this.descending = descending;
458             this.size = size;
459             this.priority = priority;
460         }
461  
462         public void paintIcon(Component c, Graphics g, int x, int y) {
463             Color color = c == null ? Color.GRAY : c.getBackground();
464             // In a compound sort, make each succesive triangle 20%
465             // smaller than the previous one.
466             int dx = (int) (size / 2 * Math.pow(0.8, priority));
467             int dy = descending ? dx : -dx;
468             // Align icon (roughly) with font baseline.
469             y = y + 5 * size / 6 + (descending ? -dy : 0);
470             int shift = descending ? 1 : -1;
471             g.translate(x, y);
472  
473             // Right diagonal.
474             g.setColor(color.darker());
475             g.drawLine(dx / 2, dy, 0, 0);
476             g.drawLine(dx / 2, dy + shift, 0, shift);
477  
478             // Left diagonal.
479             g.setColor(color.brighter());
480             g.drawLine(dx / 2, dy, dx, 0);
481             g.drawLine(dx / 2, dy + shift, dx, shift);
482  
483             // Horizontal line.
484             if (descending) {
485                 g.setColor(color.darker().darker());
486             } else {
487                 g.setColor(color.brighter().brighter());
488             }
489             g.drawLine(dx, 0, 0, 0);
490  
491             g.setColor(color);
492             g.translate(-x, -y);
493         }
494  
495         public int getIconWidth() {
496             return size;
497         }
498  
499         public int getIconHeight() {
500             return size;
501         }
502     }
503  
504     private class SortableHeaderRenderer implements TableCellRenderer {
505         private TableCellRenderer tableCellRenderer;
506  
507         public SortableHeaderRenderer(TableCellRenderer tableCellRenderer) {
508             this.tableCellRenderer = tableCellRenderer;
509         }
510  
511         public Component getTableCellRendererComponent(JTable table,
512                 Object value, boolean isSelected, boolean hasFocus, int row,
513                 int column) {
514             Component c = tableCellRenderer.getTableCellRendererComponent(
515                     table, value, isSelected, hasFocus, row, column);
516             if (c instanceof JLabel) {
517                 JLabel l = (JLabel) c;
518                 l.setHorizontalTextPosition(JLabel.LEFT);
519                 int modelColumn = table.convertColumnIndexToModel(column);
520                 l.setIcon(getHeaderRendererIcon(modelColumn, l.getFont()
521                         .getSize()));
522             }
523             return c;
524         }
525     }
526  
527     private static class Directive {
528         private int column;
529  
530         private int direction;
531  
532         public Directive(int column, int direction) {
533             this.column = column;
534             this.direction = direction;
535         }
536     }
537 }

this report was generated by version 1.0.5 of jcoverage.
visit www.jcoverage.com for updates.

copyright © 2003, jcoverage ltd. all rights reserved.
Java is a trademark of Sun Microsystems, Inc. in the United States and other countries.