View | Details | Raw Unified | Return to bug 52962
Collapse All | Expand All

(-)a/src/components/org/apache/jmeter/visualizers/SummaryReport.java (-2 / +5 lines)
Lines 53-58 Link Here
53
import org.apache.jorphan.gui.ObjectTableModel;
53
import org.apache.jorphan.gui.ObjectTableModel;
54
import org.apache.jorphan.gui.RateRenderer;
54
import org.apache.jorphan.gui.RateRenderer;
55
import org.apache.jorphan.gui.RendererUtils;
55
import org.apache.jorphan.gui.RendererUtils;
56
import org.apache.jorphan.gui.TableSorter;
56
import org.apache.jorphan.reflect.Functor;
57
import org.apache.jorphan.reflect.Functor;
57
import org.apache.jorphan.util.JOrphanUtils;
58
import org.apache.jorphan.util.JOrphanUtils;
58
59
Lines 237-245 Link Here
237
        mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
238
        mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
238
239
239
        mainPanel.add(makeTitlePanel());
240
        mainPanel.add(makeTitlePanel());
240
241
        TableSorter sorterIn = new TableSorter(model); 
241
        myJTable = new JTable(model);
242
        myJTable = new JTable(sorterIn);
242
        myJTable.getTableHeader().setDefaultRenderer(new HeaderAsPropertyRenderer());
243
        myJTable.getTableHeader().setDefaultRenderer(new HeaderAsPropertyRenderer());
244
        sorterIn.setTableHeader(myJTable.getTableHeader());
245
        
243
        myJTable.setPreferredScrollableViewportSize(new Dimension(500, 70));
246
        myJTable.setPreferredScrollableViewportSize(new Dimension(500, 70));
244
        RendererUtils.applyRenderers(myJTable, RENDERERS);
247
        RendererUtils.applyRenderers(myJTable, RENDERERS);
245
        myScrollPane = new JScrollPane(myJTable);
248
        myScrollPane = new JScrollPane(myJTable);
(-)a/src/jorphan/org/apache/jorphan/gui/TableSorter.java (+514 lines)
Line 0 Link Here
1
package org.apache.jorphan.gui;
2
3
/*
4
 * Copyright (c) 1995, 2008, Oracle and/or its affiliates. All rights reserved.
5
 *
6
 * Redistribution and use in source and binary forms, with or without
7
 * modification, are permitted provided that the following conditions
8
 * are met:
9
 *
10
 *   - Redistributions of source code must retain the above copyright
11
 *     notice, this list of conditions and the following disclaimer.
12
 *
13
 *   - Redistributions in binary form must reproduce the above copyright
14
 *     notice, this list of conditions and the following disclaimer in the
15
 *     documentation and/or other materials provided with the distribution.
16
 *
17
 *   - Neither the name of Oracle or the names of its
18
 *     contributors may be used to endorse or promote products derived
19
 *     from this software without specific prior written permission.
20
 *
21
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
22
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
23
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
24
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
25
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
26
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
27
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
28
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
29
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
30
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
31
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32
 */ 
33
34
import java.awt.*;
35
import java.awt.event.*;
36
import java.util.*;
37
import java.util.List;
38
39
import javax.swing.*;
40
import javax.swing.event.TableModelEvent;
41
import javax.swing.event.TableModelListener;
42
import javax.swing.table.*;
43
44
/**
45
 * TableSorter is a decorator for TableModels; adding sorting
46
 * functionality to a supplied TableModel. TableSorter does
47
 * not store or copy the data in its TableModel; instead it maintains
48
 * a map from the row indexes of the view to the row indexes of the
49
 * model. As requests are made of the sorter (like getValueAt(row, col))
50
 * they are passed to the underlying model after the row numbers
51
 * have been translated via the internal mapping array. This way,
52
 * the TableSorter appears to hold another copy of the table
53
 * with the rows in a different order.
54
 * <p/>
55
 * TableSorter registers itself as a listener to the underlying model,
56
 * just as the JTable itself would. Events recieved from the model
57
 * are examined, sometimes manipulated (typically widened), and then
58
 * passed on to the TableSorter's listeners (typically the JTable).
59
 * If a change to the model has invalidated the order of TableSorter's
60
 * rows, a note of this is made and the sorter will resort the
61
 * rows the next time a value is requested.
62
 * <p/>
63
 * When the tableHeader property is set, either by using the
64
 * setTableHeader() method or the two argument constructor, the
65
 * table header may be used as a complete UI for TableSorter.
66
 * The default renderer of the tableHeader is decorated with a renderer
67
 * that indicates the sorting status of each column. In addition,
68
 * a mouse listener is installed with the following behavior:
69
 * <ul>
70
 * <li>
71
 * Mouse-click: Clears the sorting status of all other columns
72
 * and advances the sorting status of that column through three
73
 * values: {NOT_SORTED, ASCENDING, DESCENDING} (then back to
74
 * NOT_SORTED again).
75
 * <li>
76
 * SHIFT-mouse-click: Clears the sorting status of all other columns
77
 * and cycles the sorting status of the column through the same
78
 * three values, in the opposite order: {NOT_SORTED, DESCENDING, ASCENDING}.
79
 * <li>
80
 * CONTROL-mouse-click and CONTROL-SHIFT-mouse-click: as above except
81
 * that the changes to the column do not cancel the statuses of columns
82
 * that are already sorting - giving a way to initiate a compound
83
 * sort.
84
 * </ul>
85
 * <p/>
86
 * This is a long overdue rewrite of a class of the same name that
87
 * first appeared in the swing table demos in 1997.
88
 * 
89
 * @author Philip Milne
90
 * @author Brendon McLean 
91
 * @author Dan van Enckevort
92
 * @author Parwinder Sekhon
93
 * @version 2.0 02/27/04
94
 */
95
96
public class TableSorter extends AbstractTableModel {
97
    protected TableModel tableModel;
98
99
    public static final int DESCENDING = -1;
100
    public static final int NOT_SORTED = 0;
101
    public static final int ASCENDING = 1;
102
103
    private static Directive EMPTY_DIRECTIVE = new Directive(-1, NOT_SORTED);
104
105
    public static final Comparator COMPARABLE_COMAPRATOR = new Comparator() {
106
        public int compare(Object o1, Object o2) {
107
            return ((Comparable) o1).compareTo(o2);
108
        }
109
    };
110
    public static final Comparator LEXICAL_COMPARATOR = new Comparator() {
111
        public int compare(Object o1, Object o2) {
112
            return o1.toString().compareTo(o2.toString());
113
        }
114
    };
115
116
    private Row[] viewToModel;
117
    private int[] modelToView;
118
119
    private JTableHeader tableHeader;
120
    private MouseListener mouseListener;
121
    private TableModelListener tableModelListener;
122
    private Map columnComparators = new HashMap();
123
    private List sortingColumns = new ArrayList();
124
125
    public TableSorter() {
126
        this.mouseListener = new MouseHandler();
127
        this.tableModelListener = new TableModelHandler();
128
    }
129
130
    public TableSorter(TableModel tableModel) {
131
        this();
132
        setTableModel(tableModel);
133
    }
134
135
    public TableSorter(TableModel tableModel, JTableHeader tableHeader) {
136
        this();
137
        setTableHeader(tableHeader);
138
        setTableModel(tableModel);
139
    }
140
141
    private void clearSortingState() {
142
        viewToModel = null;
143
        modelToView = null;
144
    }
145
146
    public TableModel getTableModel() {
147
        return tableModel;
148
    }
149
150
    public void setTableModel(TableModel tableModel) {
151
        if (this.tableModel != null) {
152
            this.tableModel.removeTableModelListener(tableModelListener);
153
        }
154
155
        this.tableModel = tableModel;
156
        if (this.tableModel != null) {
157
            this.tableModel.addTableModelListener(tableModelListener);
158
        }
159
160
        clearSortingState();
161
        fireTableStructureChanged();
162
    }
163
164
    public JTableHeader getTableHeader() {
165
        return tableHeader;
166
    }
167
168
    public void setTableHeader(JTableHeader tableHeader) {
169
        if (this.tableHeader != null) {
170
            this.tableHeader.removeMouseListener(mouseListener);
171
            TableCellRenderer defaultRenderer = this.tableHeader.getDefaultRenderer();
172
            if (defaultRenderer instanceof SortableHeaderRenderer) {
173
                this.tableHeader.setDefaultRenderer(((SortableHeaderRenderer) defaultRenderer).tableCellRenderer);
174
            }
175
        }
176
        this.tableHeader = tableHeader;
177
        if (this.tableHeader != null) {
178
            this.tableHeader.addMouseListener(mouseListener);
179
            this.tableHeader.setDefaultRenderer(
180
                    new SortableHeaderRenderer(this.tableHeader.getDefaultRenderer()));
181
        }
182
    }
183
184
    public boolean isSorting() {
185
        return sortingColumns.size() != 0;
186
    }
187
188
    private Directive getDirective(int column) {
189
        for (int i = 0; i < sortingColumns.size(); i++) {
190
            Directive directive = (Directive)sortingColumns.get(i);
191
            if (directive.column == column) {
192
                return directive;
193
            }
194
        }
195
        return EMPTY_DIRECTIVE;
196
    }
197
198
    public int getSortingStatus(int column) {
199
        return getDirective(column).direction;
200
    }
201
202
    private void sortingStatusChanged() {
203
        clearSortingState();
204
        fireTableDataChanged();
205
        if (tableHeader != null) {
206
            tableHeader.repaint();
207
        }
208
    }
209
210
    public void setSortingStatus(int column, int status) {
211
        Directive directive = getDirective(column);
212
        if (directive != EMPTY_DIRECTIVE) {
213
            sortingColumns.remove(directive);
214
        }
215
        if (status != NOT_SORTED) {
216
            sortingColumns.add(new Directive(column, status));
217
        }
218
        sortingStatusChanged();
219
    }
220
221
    protected Icon getHeaderRendererIcon(int column, int size) {
222
        Directive directive = getDirective(column);
223
        if (directive == EMPTY_DIRECTIVE) {
224
            return null;
225
        }
226
        return new Arrow(directive.direction == DESCENDING, size, sortingColumns.indexOf(directive));
227
    }
228
229
    private void cancelSorting() {
230
        sortingColumns.clear();
231
        sortingStatusChanged();
232
    }
233
234
    public void setColumnComparator(Class type, Comparator comparator) {
235
        if (comparator == null) {
236
            columnComparators.remove(type);
237
        } else {
238
            columnComparators.put(type, comparator);
239
        }
240
    }
241
242
    protected Comparator getComparator(int column) {
243
        Class columnType = tableModel.getColumnClass(column);
244
        Comparator comparator = (Comparator) columnComparators.get(columnType);
245
        if (comparator != null) {
246
            return comparator;
247
        }
248
        if (Comparable.class.isAssignableFrom(columnType)) {
249
            return COMPARABLE_COMAPRATOR;
250
        }
251
        return LEXICAL_COMPARATOR;
252
    }
253
254
    private Row[] getViewToModel() {
255
        if (viewToModel == null) {
256
            int tableModelRowCount = tableModel.getRowCount();
257
            viewToModel = new Row[tableModelRowCount];
258
            for (int row = 0; row < tableModelRowCount; row++) {
259
                viewToModel[row] = new Row(row);
260
            }
261
262
            if (isSorting()) {
263
                Arrays.sort(viewToModel);
264
            }
265
        }
266
        return viewToModel;
267
    }
268
269
    public int modelIndex(int viewIndex) {
270
        return getViewToModel()[viewIndex].modelIndex;
271
    }
272
273
    private int[] getModelToView() {
274
        if (modelToView == null) {
275
            int n = getViewToModel().length;
276
            modelToView = new int[n];
277
            for (int i = 0; i < n; i++) {
278
                modelToView[modelIndex(i)] = i;
279
            }
280
        }
281
        return modelToView;
282
    }
283
284
    // TableModel interface methods 
285
286
    public int getRowCount() {
287
        return (tableModel == null) ? 0 : tableModel.getRowCount();
288
    }
289
290
    public int getColumnCount() {
291
        return (tableModel == null) ? 0 : tableModel.getColumnCount();
292
    }
293
294
    public String getColumnName(int column) {
295
        return tableModel.getColumnName(column);
296
    }
297
298
    public Class getColumnClass(int column) {
299
        return tableModel.getColumnClass(column);
300
    }
301
302
    public boolean isCellEditable(int row, int column) {
303
        return tableModel.isCellEditable(modelIndex(row), column);
304
    }
305
306
    public Object getValueAt(int row, int column) {
307
        return tableModel.getValueAt(modelIndex(row), column);
308
    }
309
310
    public void setValueAt(Object aValue, int row, int column) {
311
        tableModel.setValueAt(aValue, modelIndex(row), column);
312
    }
313
314
    // Helper classes
315
    
316
    private class Row implements Comparable {
317
        private int modelIndex;
318
319
        public Row(int index) {
320
            this.modelIndex = index;
321
        }
322
323
        public int compareTo(Object o) {
324
            int row1 = modelIndex;
325
            int row2 = ((Row) o).modelIndex;
326
327
            for (Iterator it = sortingColumns.iterator(); it.hasNext();) {
328
                Directive directive = (Directive) it.next();
329
                int column = directive.column;
330
                Object o1 = tableModel.getValueAt(row1, column);
331
                Object o2 = tableModel.getValueAt(row2, column);
332
333
                int comparison = 0;
334
                // Define null less than everything, except null.
335
                if (o1 == null && o2 == null) {
336
                    comparison = 0;
337
                } else if (o1 == null) {
338
                    comparison = -1;
339
                } else if (o2 == null) {
340
                    comparison = 1;
341
                } else {
342
                    comparison = getComparator(column).compare(o1, o2);
343
                }
344
                if (comparison != 0) {
345
                    return directive.direction == DESCENDING ? -comparison : comparison;
346
                }
347
            }
348
            return 0;
349
        }
350
    }
351
352
    private class TableModelHandler implements TableModelListener {
353
        public void tableChanged(TableModelEvent e) {
354
            // If we're not sorting by anything, just pass the event along.             
355
            if (!isSorting()) {
356
                clearSortingState();
357
                fireTableChanged(e);
358
                return;
359
            }
360
                
361
            // If the table structure has changed, cancel the sorting; the             
362
            // sorting columns may have been either moved or deleted from             
363
            // the model. 
364
            if (e.getFirstRow() == TableModelEvent.HEADER_ROW) {
365
                cancelSorting();
366
                fireTableChanged(e);
367
                return;
368
            }
369
370
            // We can map a cell event through to the view without widening             
371
            // when the following conditions apply: 
372
            // 
373
            // a) all the changes are on one row (e.getFirstRow() == e.getLastRow()) and, 
374
            // b) all the changes are in one column (column != TableModelEvent.ALL_COLUMNS) and,
375
            // c) we are not sorting on that column (getSortingStatus(column) == NOT_SORTED) and, 
376
            // d) a reverse lookup will not trigger a sort (modelToView != null)
377
            //
378
            // Note: INSERT and DELETE events fail this test as they have column == ALL_COLUMNS.
379
            // 
380
            // The last check, for (modelToView != null) is to see if modelToView 
381
            // is already allocated. If we don't do this check; sorting can become 
382
            // a performance bottleneck for applications where cells  
383
            // change rapidly in different parts of the table. If cells 
384
            // change alternately in the sorting column and then outside of             
385
            // it this class can end up re-sorting on alternate cell updates - 
386
            // which can be a performance problem for large tables. The last 
387
            // clause avoids this problem. 
388
            int column = e.getColumn();
389
            if (e.getFirstRow() == e.getLastRow()
390
                    && column != TableModelEvent.ALL_COLUMNS
391
                    && getSortingStatus(column) == NOT_SORTED
392
                    && modelToView != null) {
393
                int viewIndex = getModelToView()[e.getFirstRow()];
394
                fireTableChanged(new TableModelEvent(TableSorter.this, 
395
                                                     viewIndex, viewIndex, 
396
                                                     column, e.getType()));
397
                return;
398
            }
399
400
            // Something has happened to the data that may have invalidated the row order. 
401
            clearSortingState();
402
            fireTableDataChanged();
403
            return;
404
        }
405
    }
406
407
    private class MouseHandler extends MouseAdapter {
408
        public void mouseClicked(MouseEvent e) {
409
            JTableHeader h = (JTableHeader) e.getSource();
410
            TableColumnModel columnModel = h.getColumnModel();
411
            int viewColumn = h.columnAtPoint(e.getPoint());
412
            int column = columnModel.getColumn(viewColumn).getModelIndex();
413
            if (column != -1) {
414
                int status = getSortingStatus(column);
415
                if (!e.isControlDown()) {
416
                    cancelSorting();
417
                }
418
                // Cycle the sorting states through {NOT_SORTED, ASCENDING, DESCENDING} or 
419
                // {NOT_SORTED, DESCENDING, ASCENDING} depending on whether shift is pressed. 
420
                status = status + (e.isShiftDown() ? -1 : 1);
421
                status = (status + 4) % 3 - 1; // signed mod, returning {-1, 0, 1}
422
                setSortingStatus(column, status);
423
            }
424
        }
425
    }
426
427
    private static class Arrow implements Icon {
428
        private boolean descending;
429
        private int size;
430
        private int priority;
431
432
        public Arrow(boolean descending, int size, int priority) {
433
            this.descending = descending;
434
            this.size = size;
435
            this.priority = priority;
436
        }
437
438
        public void paintIcon(Component c, Graphics g, int x, int y) {
439
            Color color = c == null ? Color.GRAY : c.getBackground();             
440
            // In a compound sort, make each succesive triangle 20% 
441
            // smaller than the previous one. 
442
            int dx = (int)(size/2*Math.pow(0.8, priority));
443
            int dy = descending ? dx : -dx;
444
            // Align icon (roughly) with font baseline. 
445
            y = y + 5*size/6 + (descending ? -dy : 0);
446
            int shift = descending ? 1 : -1;
447
            g.translate(x, y);
448
449
            // Right diagonal. 
450
            g.setColor(color.darker());
451
            g.drawLine(dx / 2, dy, 0, 0);
452
            g.drawLine(dx / 2, dy + shift, 0, shift);
453
            
454
            // Left diagonal. 
455
            g.setColor(color.brighter());
456
            g.drawLine(dx / 2, dy, dx, 0);
457
            g.drawLine(dx / 2, dy + shift, dx, shift);
458
            
459
            // Horizontal line. 
460
            if (descending) {
461
                g.setColor(color.darker().darker());
462
            } else {
463
                g.setColor(color.brighter().brighter());
464
            }
465
            g.drawLine(dx, 0, 0, 0);
466
467
            g.setColor(color);
468
            g.translate(-x, -y);
469
        }
470
471
        public int getIconWidth() {
472
            return size;
473
        }
474
475
        public int getIconHeight() {
476
            return size;
477
        }
478
    }
479
480
    private class SortableHeaderRenderer implements TableCellRenderer {
481
        private TableCellRenderer tableCellRenderer;
482
483
        public SortableHeaderRenderer(TableCellRenderer tableCellRenderer) {
484
            this.tableCellRenderer = tableCellRenderer;
485
        }
486
487
        public Component getTableCellRendererComponent(JTable table, 
488
                                                       Object value,
489
                                                       boolean isSelected, 
490
                                                       boolean hasFocus,
491
                                                       int row, 
492
                                                       int column) {
493
            Component c = tableCellRenderer.getTableCellRendererComponent(table, 
494
                    value, isSelected, hasFocus, row, column);
495
            if (c instanceof JLabel) {
496
                JLabel l = (JLabel) c;
497
                l.setHorizontalTextPosition(JLabel.LEFT);
498
                int modelColumn = table.convertColumnIndexToModel(column);
499
                l.setIcon(getHeaderRendererIcon(modelColumn, l.getFont().getSize()));
500
            }
501
            return c;
502
        }
503
    }
504
505
    private static class Directive {
506
        private int column;
507
        private int direction;
508
509
        public Directive(int column, int direction) {
510
            this.column = column;
511
            this.direction = direction;
512
        }
513
    }
514
}

Return to bug 52962