Statistics
| Revision:

svn-gvsig-desktop / trunk / org.gvsig.desktop / org.gvsig.desktop.plugin / org.gvsig.app / org.gvsig.app.mainplugin / src / main / java / org / gvsig / app / gui / TableSorter.java @ 40558

History | View | Annotate | Download (18.5 KB)

1
/**
2
 * gvSIG. Desktop Geographic Information System.
3
 *
4
 * Copyright (C) 2007-2013 gvSIG Association.
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 3
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,
19
 * MA  02110-1301, USA.
20
 *
21
 * For any additional information, do not hesitate to contact us
22
 * at info AT gvsig.com, or visit our website www.gvsig.com.
23
 */
24
package org.gvsig.app.gui;
25

    
26
import java.awt.Color;
27
import java.awt.Component;
28
import java.awt.Graphics;
29
import java.awt.event.MouseAdapter;
30
import java.awt.event.MouseEvent;
31
import java.awt.event.MouseListener;
32
import java.util.ArrayList;
33
import java.util.Arrays;
34
import java.util.Comparator;
35
import java.util.HashMap;
36
import java.util.Iterator;
37
import java.util.List;
38
import java.util.Map;
39

    
40
import javax.swing.Icon;
41
import javax.swing.JLabel;
42
import javax.swing.JTable;
43
import javax.swing.event.TableModelEvent;
44
import javax.swing.event.TableModelListener;
45
import javax.swing.table.AbstractTableModel;
46
import javax.swing.table.JTableHeader;
47
import javax.swing.table.TableCellRenderer;
48
import javax.swing.table.TableColumnModel;
49
import javax.swing.table.TableModel;
50

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

    
103
public class TableSorter extends AbstractTableModel {
104
    protected TableModel tableModel;
105

    
106
    public static final int DESCENDING = -1;
107
    public static final int NOT_SORTED = 0;
108
    public static final int ASCENDING = 1;
109

    
110
    private static Directive EMPTY_DIRECTIVE = new Directive(-1, NOT_SORTED);
111

    
112
    public static final Comparator COMPARABLE_COMAPRATOR = new Comparator() {
113
        public int compare(Object o1, Object o2) {
114
            return ((Comparable) o1).compareTo(o2);
115
        }
116
    };
117
    public static final Comparator LEXICAL_COMPARATOR = new Comparator() {
118
        public int compare(Object o1, Object o2) {
119
            return o1.toString().compareTo(o2.toString());
120
        }
121
    };
122

    
123
    private Row[] viewToModel;
124
    private int[] modelToView;
125

    
126
    private JTableHeader tableHeader;
127
    private MouseListener mouseListener;
128
    private TableModelListener tableModelListener;
129
    private Map columnComparators = new HashMap();
130
    private List sortingColumns = new ArrayList();
131

    
132
    public TableSorter() {
133
        this.mouseListener = new MouseHandler();
134
        this.tableModelListener = new TableModelHandler();
135
    }
136

    
137
    public TableSorter(TableModel tableModel) {
138
        this();
139
        setTableModel(tableModel);
140
    }
141

    
142
    public TableSorter(TableModel tableModel, JTableHeader tableHeader) {
143
        this();
144
        setTableHeader(tableHeader);
145
        setTableModel(tableModel);
146
    }
147

    
148
    private void clearSortingState() {
149
        viewToModel = null;
150
        modelToView = null;
151
    }
152

    
153
    public TableModel getTableModel() {
154
        return tableModel;
155
    }
156

    
157
    public void setTableModel(TableModel tableModel) {
158
        if (this.tableModel != null) {
159
            this.tableModel.removeTableModelListener(tableModelListener);
160
        }
161

    
162
        this.tableModel = tableModel;
163
        if (this.tableModel != null) {
164
            this.tableModel.addTableModelListener(tableModelListener);
165
        }
166

    
167
        clearSortingState();
168
        fireTableStructureChanged();
169
    }
170

    
171
    public JTableHeader getTableHeader() {
172
        return tableHeader;
173
    }
174

    
175
    public void setTableHeader(JTableHeader tableHeader) {
176
        if (this.tableHeader != null) {
177
            this.tableHeader.removeMouseListener(mouseListener);
178
            TableCellRenderer defaultRenderer = this.tableHeader.getDefaultRenderer();
179
            if (defaultRenderer instanceof SortableHeaderRenderer) {
180
                this.tableHeader.setDefaultRenderer(((SortableHeaderRenderer) defaultRenderer).tableCellRenderer);
181
            }
182
        }
183
        this.tableHeader = tableHeader;
184
        if (this.tableHeader != null) {
185
            this.tableHeader.addMouseListener(mouseListener);
186
            this.tableHeader.setDefaultRenderer(
187
                    new SortableHeaderRenderer(this.tableHeader.getDefaultRenderer()));
188
        }
189
    }
190

    
191
    public boolean isSorting() {
192
        return sortingColumns.size() != 0;
193
    }
194

    
195
    private Directive getDirective(int column) {
196
        for (int i = 0; i < sortingColumns.size(); i++) {
197
            Directive directive = (Directive)sortingColumns.get(i);
198
            if (directive.column == column) {
199
                return directive;
200
            }
201
        }
202
        return EMPTY_DIRECTIVE;
203
    }
204

    
205
    public int getSortingStatus(int column) {
206
        return getDirective(column).direction;
207
    }
208

    
209
    private void sortingStatusChanged() {
210
        clearSortingState();
211
        fireTableDataChanged();
212
        if (tableHeader != null) {
213
            tableHeader.repaint();
214
        }
215
    }
216

    
217
    public void setSortingStatus(int column, int status) {
218
        Directive directive = getDirective(column);
219
        if (directive != EMPTY_DIRECTIVE) {
220
            sortingColumns.remove(directive);
221
        }
222
        if (status != NOT_SORTED) {
223
            sortingColumns.add(new Directive(column, status));
224
        }
225
        sortingStatusChanged();
226
    }
227

    
228
    protected Icon getHeaderRendererIcon(int column, int size) {
229
        Directive directive = getDirective(column);
230
        if (directive == EMPTY_DIRECTIVE) {
231
            return null;
232
        }
233
        return new Arrow(directive.direction == DESCENDING, size, sortingColumns.indexOf(directive));
234
    }
235

    
236
    private void cancelSorting() {
237
        sortingColumns.clear();
238
        sortingStatusChanged();
239
    }
240

    
241
    public void setColumnComparator(Class type, Comparator comparator) {
242
        if (comparator == null) {
243
            columnComparators.remove(type);
244
        } else {
245
            columnComparators.put(type, comparator);
246
        }
247
    }
248

    
249
    protected Comparator getComparator(int column) {
250
        Class columnType = tableModel.getColumnClass(column);
251
        Comparator comparator = (Comparator) columnComparators.get(columnType);
252
        if (comparator != null) {
253
            return comparator;
254
        }
255
        if (Comparable.class.isAssignableFrom(columnType)) {
256
            return COMPARABLE_COMAPRATOR;
257
        }
258
        return LEXICAL_COMPARATOR;
259
    }
260

    
261
    private Row[] getViewToModel() {
262
        if (viewToModel == null) {
263
            int tableModelRowCount = tableModel.getRowCount();
264
            viewToModel = new Row[tableModelRowCount];
265
            for (int row = 0; row < tableModelRowCount; row++) {
266
                viewToModel[row] = new Row(row);
267
            }
268

    
269
            if (isSorting()) {
270
                Arrays.sort(viewToModel);
271
            }
272
        }
273
        return viewToModel;
274
    }
275

    
276
    public int modelIndex(int viewIndex) {
277
        return getViewToModel()[viewIndex].modelIndex;
278
    }
279

    
280
    private int[] getModelToView() {
281
        if (modelToView == null) {
282
            int n = getViewToModel().length;
283
            modelToView = new int[n];
284
            for (int i = 0; i < n; i++) {
285
                modelToView[modelIndex(i)] = i;
286
            }
287
        }
288
        return modelToView;
289
    }
290

    
291
    // TableModel interface methods 
292

    
293
    public int getRowCount() {
294
        return (tableModel == null) ? 0 : tableModel.getRowCount();
295
    }
296

    
297
    public int getColumnCount() {
298
        return (tableModel == null) ? 0 : tableModel.getColumnCount();
299
    }
300

    
301
    public String getColumnName(int column) {
302
        return tableModel.getColumnName(column);
303
    }
304

    
305
    public Class getColumnClass(int column) {
306
        return tableModel.getColumnClass(column);
307
    }
308

    
309
    public boolean isCellEditable(int row, int column) {
310
        return tableModel.isCellEditable(modelIndex(row), column);
311
    }
312

    
313
    public Object getValueAt(int row, int column) {
314
        return tableModel.getValueAt(modelIndex(row), column);
315
    }
316

    
317
    public void setValueAt(Object aValue, int row, int column) {
318
        tableModel.setValueAt(aValue, modelIndex(row), column);
319
    }
320

    
321
    // Helper classes
322
    
323
    private class Row implements Comparable {
324
        private int modelIndex;
325

    
326
        public Row(int index) {
327
            this.modelIndex = index;
328
        }
329

    
330
        public int compareTo(Object o) {
331
            int row1 = modelIndex;
332
            int row2 = ((Row) o).modelIndex;
333

    
334
            for (Iterator it = sortingColumns.iterator(); it.hasNext();) {
335
                Directive directive = (Directive) it.next();
336
                int column = directive.column;
337
                Object o1 = tableModel.getValueAt(row1, column);
338
                Object o2 = tableModel.getValueAt(row2, column);
339

    
340
                int comparison = 0;
341
                // Define null less than everything, except null.
342
                if (o1 == null && o2 == null) {
343
                    comparison = 0;
344
                } else if (o1 == null) {
345
                    comparison = -1;
346
                } else if (o2 == null) {
347
                    comparison = 1;
348
                } else {
349
                    comparison = getComparator(column).compare(o1, o2);
350
                }
351
                if (comparison != 0) {
352
                    return directive.direction == DESCENDING ? -comparison : comparison;
353
                }
354
            }
355
            return 0;
356
        }
357
    }
358

    
359
    private class TableModelHandler implements TableModelListener {
360
        public void tableChanged(TableModelEvent e) {
361
            // If we're not sorting by anything, just pass the event along.             
362
            if (!isSorting()) {
363
                clearSortingState();
364
                fireTableChanged(e);
365
                return;
366
            }
367
                
368
            // If the table structure has changed, cancel the sorting; the             
369
            // sorting columns may have been either moved or deleted from             
370
            // the model. 
371
            if (e.getFirstRow() == TableModelEvent.HEADER_ROW) {
372
                cancelSorting();
373
                fireTableChanged(e);
374
                return;
375
            }
376

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

    
407
            // Something has happened to the data that may have invalidated the row order. 
408
            clearSortingState();
409
            fireTableDataChanged();
410
            return;
411
        }
412
    }
413

    
414
    private class MouseHandler extends MouseAdapter {
415
        public void mouseClicked(MouseEvent e) {
416
            JTableHeader h = (JTableHeader) e.getSource();
417
            TableColumnModel columnModel = h.getColumnModel();
418
            int viewColumn = columnModel.getColumnIndexAtX(e.getX());
419
            int column = columnModel.getColumn(viewColumn).getModelIndex();
420
            if (column != -1) {
421
                int status = getSortingStatus(column);
422
                if (!e.isControlDown()) {
423
                    cancelSorting();
424
                }
425
                // Cycle the sorting states through {NOT_SORTED, ASCENDING, DESCENDING} or 
426
                // {NOT_SORTED, DESCENDING, ASCENDING} depending on whether shift is pressed. 
427
                status = status + (e.isShiftDown() ? -1 : 1);
428
                status = (status + 4) % 3 - 1; // signed mod, returning {-1, 0, 1}
429
                setSortingStatus(column, status);
430
            }
431
        }
432
    }
433

    
434
    private static class Arrow implements Icon {
435
        private boolean descending;
436
        private int size;
437
        private int priority;
438

    
439
        public Arrow(boolean descending, int size, int priority) {
440
            this.descending = descending;
441
            this.size = size;
442
            this.priority = priority;
443
        }
444

    
445
        public void paintIcon(Component c, Graphics g, int x, int y) {
446
            Color color = c == null ? Color.GRAY : c.getBackground();             
447
            // In a compound sort, make each succesive triangle 20% 
448
            // smaller than the previous one. 
449
            int dx = (int)(size/2*Math.pow(0.8, priority));
450
            int dy = descending ? dx : -dx;
451
            // Align icon (roughly) with font baseline. 
452
            y = y + 5*size/6 + (descending ? -dy : 0);
453
            int shift = descending ? 1 : -1;
454
            g.translate(x, y);
455

    
456
            // Right diagonal. 
457
            g.setColor(color.darker());
458
            g.drawLine(dx / 2, dy, 0, 0);
459
            g.drawLine(dx / 2, dy + shift, 0, shift);
460
            
461
            // Left diagonal. 
462
            g.setColor(color.brighter());
463
            g.drawLine(dx / 2, dy, dx, 0);
464
            g.drawLine(dx / 2, dy + shift, dx, shift);
465
            
466
            // Horizontal line. 
467
            if (descending) {
468
                g.setColor(color.darker().darker());
469
            } else {
470
                g.setColor(color.brighter().brighter());
471
            }
472
            g.drawLine(dx, 0, 0, 0);
473

    
474
            g.setColor(color);
475
            g.translate(-x, -y);
476
        }
477

    
478
        public int getIconWidth() {
479
            return size;
480
        }
481

    
482
        public int getIconHeight() {
483
            return size;
484
        }
485
    }
486

    
487
    private class SortableHeaderRenderer implements TableCellRenderer {
488
        private TableCellRenderer tableCellRenderer;
489

    
490
        public SortableHeaderRenderer(TableCellRenderer tableCellRenderer) {
491
            this.tableCellRenderer = tableCellRenderer;
492
        }
493

    
494
        public Component getTableCellRendererComponent(JTable table, 
495
                                                       Object value,
496
                                                       boolean isSelected, 
497
                                                       boolean hasFocus,
498
                                                       int row, 
499
                                                       int column) {
500
            Component c = tableCellRenderer.getTableCellRendererComponent(table, 
501
                    value, isSelected, hasFocus, row, column);
502
            if (c instanceof JLabel) {
503
                JLabel l = (JLabel) c;
504
                l.setHorizontalTextPosition(JLabel.LEFT);
505
                int modelColumn = table.convertColumnIndexToModel(column);
506
                l.setIcon(getHeaderRendererIcon(modelColumn, l.getFont().getSize()));
507
            }
508
            return c;
509
        }
510
    }
511

    
512
    private static class Directive {
513
        private int column;
514
        private int direction;
515

    
516
        public Directive(int column, int direction) {
517
            this.column = column;
518
            this.direction = direction;
519
        }
520
    }
521
}