Statistics
| Revision:

svn-gvsig-desktop / tags / v1_0_1_RELEASE / applications / appgvSIG / src / com / iver / cit / gvsig / gui / TableSorter.java @ 9531

History | View | Annotate | Download (18.8 KB)

1
/* gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
2
 *
3
 * Copyright (C) 2004 IVER T.I. and Generalitat Valenciana.
4
 *
5
 * This program is free software; you can redistribute it and/or
6
 * modify it under the terms of the GNU General Public License
7
 * as published by the Free Software Foundation; either version 2
8
 * of the License, or (at your option) any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with this program; if not, write to the Free Software
17
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,USA.
18
 *
19
 * For more information, contact:
20
 *
21
 *  Generalitat Valenciana
22
 *   Conselleria d'Infraestructures i Transport
23
 *   Av. Blasco Ib??ez, 50
24
 *   46010 VALENCIA
25
 *   SPAIN
26
 *
27
 *      +34 963862235
28
 *   gvsig@gva.es
29
 *      www.gvsig.gva.es
30
 *
31
 *    or
32
 *
33
 *   IVER T.I. S.A
34
 *   Salamanca 50
35
 *   46005 Valencia
36
 *   Spain
37
 *
38
 *   +34 963163400
39
 *   dac@iver.es
40
 */
41
package com.iver.cit.gvsig.gui;
42

    
43
import java.awt.Color;
44
import java.awt.Component;
45
import java.awt.Graphics;
46
import java.awt.event.MouseAdapter;
47
import java.awt.event.MouseEvent;
48
import java.awt.event.MouseListener;
49
import java.util.ArrayList;
50
import java.util.Arrays;
51
import java.util.Comparator;
52
import java.util.HashMap;
53
import java.util.Iterator;
54
import java.util.List;
55
import java.util.Map;
56

    
57
import javax.swing.Icon;
58
import javax.swing.JLabel;
59
import javax.swing.JTable;
60
import javax.swing.event.TableModelEvent;
61
import javax.swing.event.TableModelListener;
62
import javax.swing.table.AbstractTableModel;
63
import javax.swing.table.JTableHeader;
64
import javax.swing.table.TableCellRenderer;
65
import javax.swing.table.TableColumnModel;
66
import javax.swing.table.TableModel;
67

    
68
/**
69
 * TableSorter is a decorator for TableModels; adding sorting
70
 * functionality to a supplied TableModel. TableSorter does
71
 * not store or copy the data in its TableModel; instead it maintains
72
 * a map from the row indexes of the view to the row indexes of the
73
 * model. As requests are made of the sorter (like getValueAt(row, col))
74
 * they are passed to the underlying model after the row numbers
75
 * have been translated via the internal mapping array. This way,
76
 * the TableSorter appears to hold another copy of the table
77
 * with the rows in a different order.
78
 * <p/>
79
 * TableSorter registers itself as a listener to the underlying model,
80
 * just as the JTable itself would. Events recieved from the model
81
 * are examined, sometimes manipulated (typically widened), and then
82
 * passed on to the TableSorter's listeners (typically the JTable).
83
 * If a change to the model has invalidated the order of TableSorter's
84
 * rows, a note of this is made and the sorter will resort the
85
 * rows the next time a value is requested.
86
 * <p/>
87
 * When the tableHeader property is set, either by using the
88
 * setTableHeader() method or the two argument constructor, the
89
 * table header may be used as a complete UI for TableSorter.
90
 * The default renderer of the tableHeader is decorated with a renderer
91
 * that indicates the sorting status of each column. In addition,
92
 * a mouse listener is installed with the following behavior:
93
 * <ul>
94
 * <li>
95
 * Mouse-click: Clears the sorting status of all other columns
96
 * and advances the sorting status of that column through three
97
 * values: {NOT_SORTED, ASCENDING, DESCENDING} (then back to
98
 * NOT_SORTED again).
99
 * <li>
100
 * SHIFT-mouse-click: Clears the sorting status of all other columns
101
 * and cycles the sorting status of the column through the same
102
 * three values, in the opposite order: {NOT_SORTED, DESCENDING, ASCENDING}.
103
 * <li>
104
 * CONTROL-mouse-click and CONTROL-SHIFT-mouse-click: as above except
105
 * that the changes to the column do not cancel the statuses of columns
106
 * that are already sorting - giving a way to initiate a compound
107
 * sort.
108
 * </ul>
109
 * <p/>
110
 * This is a long overdue rewrite of a class of the same name that
111
 * first appeared in the swing table demos in 1997.
112
 * 
113
 * @author Philip Milne
114
 * @author Brendon McLean 
115
 * @author Dan van Enckevort
116
 * @author Parwinder Sekhon
117
 * @version 2.0 02/27/04
118
 */
119

    
120
public class TableSorter extends AbstractTableModel {
121
    protected TableModel tableModel;
122

    
123
    public static final int DESCENDING = -1;
124
    public static final int NOT_SORTED = 0;
125
    public static final int ASCENDING = 1;
126

    
127
    private static Directive EMPTY_DIRECTIVE = new Directive(-1, NOT_SORTED);
128

    
129
    public static final Comparator COMPARABLE_COMAPRATOR = new Comparator() {
130
        public int compare(Object o1, Object o2) {
131
            return ((Comparable) o1).compareTo(o2);
132
        }
133
    };
134
    public static final Comparator LEXICAL_COMPARATOR = new Comparator() {
135
        public int compare(Object o1, Object o2) {
136
            return o1.toString().compareTo(o2.toString());
137
        }
138
    };
139

    
140
    private Row[] viewToModel;
141
    private int[] modelToView;
142

    
143
    private JTableHeader tableHeader;
144
    private MouseListener mouseListener;
145
    private TableModelListener tableModelListener;
146
    private Map columnComparators = new HashMap();
147
    private List sortingColumns = new ArrayList();
148

    
149
    public TableSorter() {
150
        this.mouseListener = new MouseHandler();
151
        this.tableModelListener = new TableModelHandler();
152
    }
153

    
154
    public TableSorter(TableModel tableModel) {
155
        this();
156
        setTableModel(tableModel);
157
    }
158

    
159
    public TableSorter(TableModel tableModel, JTableHeader tableHeader) {
160
        this();
161
        setTableHeader(tableHeader);
162
        setTableModel(tableModel);
163
    }
164

    
165
    private void clearSortingState() {
166
        viewToModel = null;
167
        modelToView = null;
168
    }
169

    
170
    public TableModel getTableModel() {
171
        return tableModel;
172
    }
173

    
174
    public void setTableModel(TableModel tableModel) {
175
        if (this.tableModel != null) {
176
            this.tableModel.removeTableModelListener(tableModelListener);
177
        }
178

    
179
        this.tableModel = tableModel;
180
        if (this.tableModel != null) {
181
            this.tableModel.addTableModelListener(tableModelListener);
182
        }
183

    
184
        clearSortingState();
185
        fireTableStructureChanged();
186
    }
187

    
188
    public JTableHeader getTableHeader() {
189
        return tableHeader;
190
    }
191

    
192
    public void setTableHeader(JTableHeader tableHeader) {
193
        if (this.tableHeader != null) {
194
            this.tableHeader.removeMouseListener(mouseListener);
195
            TableCellRenderer defaultRenderer = this.tableHeader.getDefaultRenderer();
196
            if (defaultRenderer instanceof SortableHeaderRenderer) {
197
                this.tableHeader.setDefaultRenderer(((SortableHeaderRenderer) defaultRenderer).tableCellRenderer);
198
            }
199
        }
200
        this.tableHeader = tableHeader;
201
        if (this.tableHeader != null) {
202
            this.tableHeader.addMouseListener(mouseListener);
203
            this.tableHeader.setDefaultRenderer(
204
                    new SortableHeaderRenderer(this.tableHeader.getDefaultRenderer()));
205
        }
206
    }
207

    
208
    public boolean isSorting() {
209
        return sortingColumns.size() != 0;
210
    }
211

    
212
    private Directive getDirective(int column) {
213
        for (int i = 0; i < sortingColumns.size(); i++) {
214
            Directive directive = (Directive)sortingColumns.get(i);
215
            if (directive.column == column) {
216
                return directive;
217
            }
218
        }
219
        return EMPTY_DIRECTIVE;
220
    }
221

    
222
    public int getSortingStatus(int column) {
223
        return getDirective(column).direction;
224
    }
225

    
226
    private void sortingStatusChanged() {
227
        clearSortingState();
228
        fireTableDataChanged();
229
        if (tableHeader != null) {
230
            tableHeader.repaint();
231
        }
232
    }
233

    
234
    public void setSortingStatus(int column, int status) {
235
        Directive directive = getDirective(column);
236
        if (directive != EMPTY_DIRECTIVE) {
237
            sortingColumns.remove(directive);
238
        }
239
        if (status != NOT_SORTED) {
240
            sortingColumns.add(new Directive(column, status));
241
        }
242
        sortingStatusChanged();
243
    }
244

    
245
    protected Icon getHeaderRendererIcon(int column, int size) {
246
        Directive directive = getDirective(column);
247
        if (directive == EMPTY_DIRECTIVE) {
248
            return null;
249
        }
250
        return new Arrow(directive.direction == DESCENDING, size, sortingColumns.indexOf(directive));
251
    }
252

    
253
    private void cancelSorting() {
254
        sortingColumns.clear();
255
        sortingStatusChanged();
256
    }
257

    
258
    public void setColumnComparator(Class type, Comparator comparator) {
259
        if (comparator == null) {
260
            columnComparators.remove(type);
261
        } else {
262
            columnComparators.put(type, comparator);
263
        }
264
    }
265

    
266
    protected Comparator getComparator(int column) {
267
        Class columnType = tableModel.getColumnClass(column);
268
        Comparator comparator = (Comparator) columnComparators.get(columnType);
269
        if (comparator != null) {
270
            return comparator;
271
        }
272
        if (Comparable.class.isAssignableFrom(columnType)) {
273
            return COMPARABLE_COMAPRATOR;
274
        }
275
        return LEXICAL_COMPARATOR;
276
    }
277

    
278
    private Row[] getViewToModel() {
279
        if (viewToModel == null) {
280
            int tableModelRowCount = tableModel.getRowCount();
281
            viewToModel = new Row[tableModelRowCount];
282
            for (int row = 0; row < tableModelRowCount; row++) {
283
                viewToModel[row] = new Row(row);
284
            }
285

    
286
            if (isSorting()) {
287
                Arrays.sort(viewToModel);
288
            }
289
        }
290
        return viewToModel;
291
    }
292

    
293
    public int modelIndex(int viewIndex) {
294
        return getViewToModel()[viewIndex].modelIndex;
295
    }
296

    
297
    private int[] getModelToView() {
298
        if (modelToView == null) {
299
            int n = getViewToModel().length;
300
            modelToView = new int[n];
301
            for (int i = 0; i < n; i++) {
302
                modelToView[modelIndex(i)] = i;
303
            }
304
        }
305
        return modelToView;
306
    }
307

    
308
    // TableModel interface methods 
309

    
310
    public int getRowCount() {
311
        return (tableModel == null) ? 0 : tableModel.getRowCount();
312
    }
313

    
314
    public int getColumnCount() {
315
        return (tableModel == null) ? 0 : tableModel.getColumnCount();
316
    }
317

    
318
    public String getColumnName(int column) {
319
        return tableModel.getColumnName(column);
320
    }
321

    
322
    public Class getColumnClass(int column) {
323
        return tableModel.getColumnClass(column);
324
    }
325

    
326
    public boolean isCellEditable(int row, int column) {
327
        return tableModel.isCellEditable(modelIndex(row), column);
328
    }
329

    
330
    public Object getValueAt(int row, int column) {
331
        return tableModel.getValueAt(modelIndex(row), column);
332
    }
333

    
334
    public void setValueAt(Object aValue, int row, int column) {
335
        tableModel.setValueAt(aValue, modelIndex(row), column);
336
    }
337

    
338
    // Helper classes
339
    
340
    private class Row implements Comparable {
341
        private int modelIndex;
342

    
343
        public Row(int index) {
344
            this.modelIndex = index;
345
        }
346

    
347
        public int compareTo(Object o) {
348
            int row1 = modelIndex;
349
            int row2 = ((Row) o).modelIndex;
350

    
351
            for (Iterator it = sortingColumns.iterator(); it.hasNext();) {
352
                Directive directive = (Directive) it.next();
353
                int column = directive.column;
354
                Object o1 = tableModel.getValueAt(row1, column);
355
                Object o2 = tableModel.getValueAt(row2, column);
356

    
357
                int comparison = 0;
358
                // Define null less than everything, except null.
359
                if (o1 == null && o2 == null) {
360
                    comparison = 0;
361
                } else if (o1 == null) {
362
                    comparison = -1;
363
                } else if (o2 == null) {
364
                    comparison = 1;
365
                } else {
366
                    comparison = getComparator(column).compare(o1, o2);
367
                }
368
                if (comparison != 0) {
369
                    return directive.direction == DESCENDING ? -comparison : comparison;
370
                }
371
            }
372
            return 0;
373
        }
374
    }
375

    
376
    private class TableModelHandler implements TableModelListener {
377
        public void tableChanged(TableModelEvent e) {
378
            // If we're not sorting by anything, just pass the event along.             
379
            if (!isSorting()) {
380
                clearSortingState();
381
                fireTableChanged(e);
382
                return;
383
            }
384
                
385
            // If the table structure has changed, cancel the sorting; the             
386
            // sorting columns may have been either moved or deleted from             
387
            // the model. 
388
            if (e.getFirstRow() == TableModelEvent.HEADER_ROW) {
389
                cancelSorting();
390
                fireTableChanged(e);
391
                return;
392
            }
393

    
394
            // We can map a cell event through to the view without widening             
395
            // when the following conditions apply: 
396
            // 
397
            // a) all the changes are on one row (e.getFirstRow() == e.getLastRow()) and, 
398
            // b) all the changes are in one column (column != TableModelEvent.ALL_COLUMNS) and,
399
            // c) we are not sorting on that column (getSortingStatus(column) == NOT_SORTED) and, 
400
            // d) a reverse lookup will not trigger a sort (modelToView != null)
401
            //
402
            // Note: INSERT and DELETE events fail this test as they have column == ALL_COLUMNS.
403
            // 
404
            // The last check, for (modelToView != null) is to see if modelToView 
405
            // is already allocated. If we don't do this check; sorting can become 
406
            // a performance bottleneck for applications where cells  
407
            // change rapidly in different parts of the table. If cells 
408
            // change alternately in the sorting column and then outside of             
409
            // it this class can end up re-sorting on alternate cell updates - 
410
            // which can be a performance problem for large tables. The last 
411
            // clause avoids this problem. 
412
            int column = e.getColumn();
413
            if (e.getFirstRow() == e.getLastRow()
414
                    && column != TableModelEvent.ALL_COLUMNS
415
                    && getSortingStatus(column) == NOT_SORTED
416
                    && modelToView != null) {
417
                int viewIndex = getModelToView()[e.getFirstRow()];
418
                fireTableChanged(new TableModelEvent(TableSorter.this, 
419
                                                     viewIndex, viewIndex, 
420
                                                     column, e.getType()));
421
                return;
422
            }
423

    
424
            // Something has happened to the data that may have invalidated the row order. 
425
            clearSortingState();
426
            fireTableDataChanged();
427
            return;
428
        }
429
    }
430

    
431
    private class MouseHandler extends MouseAdapter {
432
        public void mouseClicked(MouseEvent e) {
433
            JTableHeader h = (JTableHeader) e.getSource();
434
            TableColumnModel columnModel = h.getColumnModel();
435
            int viewColumn = columnModel.getColumnIndexAtX(e.getX());
436
            int column = columnModel.getColumn(viewColumn).getModelIndex();
437
            if (column != -1) {
438
                int status = getSortingStatus(column);
439
                if (!e.isControlDown()) {
440
                    cancelSorting();
441
                }
442
                // Cycle the sorting states through {NOT_SORTED, ASCENDING, DESCENDING} or 
443
                // {NOT_SORTED, DESCENDING, ASCENDING} depending on whether shift is pressed. 
444
                status = status + (e.isShiftDown() ? -1 : 1);
445
                status = (status + 4) % 3 - 1; // signed mod, returning {-1, 0, 1}
446
                setSortingStatus(column, status);
447
            }
448
        }
449
    }
450

    
451
    private static class Arrow implements Icon {
452
        private boolean descending;
453
        private int size;
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,
513
                                                       boolean isSelected, 
514
                                                       boolean hasFocus,
515
                                                       int row, 
516
                                                       int column) {
517
            Component c = tableCellRenderer.getTableCellRendererComponent(table, 
518
                    value, isSelected, hasFocus, row, column);
519
            if (c instanceof JLabel) {
520
                JLabel l = (JLabel) c;
521
                l.setHorizontalTextPosition(JLabel.LEFT);
522
                int modelColumn = table.convertColumnIndexToModel(column);
523
                l.setIcon(getHeaderRendererIcon(modelColumn, l.getFont().getSize()));
524
            }
525
            return c;
526
        }
527
    }
528

    
529
    private static class Directive {
530
        private int column;
531
        private int direction;
532

    
533
        public Directive(int column, int direction) {
534
            this.column = column;
535
            this.direction = direction;
536
        }
537
    }
538
}