KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > TableSorter


1 /*
2  * @(#)TableSorter.java 1.15 05/11/17
3  *
4  * Copyright (c) 2006 Sun Microsystems, Inc. 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 are met:
8  *
9  * -Redistribution of source code must retain the above copyright notice, this
10  * list of conditions and the following disclaimer.
11  *
12  * -Redistribution in binary form must reproduce the above copyright notice,
13  * this list of conditions and the following disclaimer in the documentation
14  * and/or other materials provided with the distribution.
15  *
16  * Neither the name of Sun Microsystems, Inc. or the names of contributors may
17  * be used to endorse or promote products derived from this software without
18  * specific prior written permission.
19  *
20  * This software is provided "AS IS," without a warranty of any kind. ALL
21  * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
22  * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
23  * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
24  * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
25  * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
26  * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
27  * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
28  * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
29  * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
30  * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
31  *
32  * You acknowledge that this software is not designed, licensed or intended
33  * for use in the design, construction, operation or maintenance of any
34  * nuclear facility.
35  */

36
37 /*
38  * @(#)TableSorter.java 1.15 05/11/17
39  */

40
41 /**
42  * A sorter for TableModels. The sorter has a model (conforming to TableModel)
43  * and itself implements TableModel. TableSorter does not store or copy
44  * the data in the TableModel, instead it maintains an array of
45  * integers which it keeps the same size as the number of rows in its
46  * model. When the model changes it notifies the sorter that something
47  * has changed eg. "rowsAdded" so that its internal array of integers
48  * can be reallocated. As requests are made of the sorter (like
49  * getValueAt(row, col) it redirects them to its model via the mapping
50  * array. That way the TableSorter appears to hold another copy of the table
51  * with the rows in a different order. The sorting algorthm used is stable
52  * which means that it does not move around rows when its comparison
53  * function returns 0 to denote that they are equivalent.
54  *
55  * @version 1.15 11/17/05
56  * @author Philip Milne
57  */

58
59 import java.util.*;
60
61 import javax.swing.table.TableModel JavaDoc;
62 import javax.swing.event.TableModelEvent JavaDoc;
63
64 // Imports for picking up mouse events from the JTable.
65

66 import java.awt.event.MouseAdapter JavaDoc;
67 import java.awt.event.MouseEvent JavaDoc;
68 import java.awt.event.InputEvent JavaDoc;
69 import javax.swing.JTable JavaDoc;
70 import javax.swing.table.JTableHeader JavaDoc;
71 import javax.swing.table.TableColumn JavaDoc;
72 import javax.swing.table.TableColumnModel JavaDoc;
73
74 public class TableSorter extends TableMap
75 {
76     int indexes[];
77     Vector sortingColumns = new Vector();
78     boolean ascending = true;
79     int compares;
80
81     public TableSorter()
82     {
83         indexes = new int[0]; // For consistency.
84
}
85
86     public TableSorter(TableModel JavaDoc model)
87     {
88         setModel(model);
89     }
90
91     public void setModel(TableModel JavaDoc model) {
92         super.setModel(model);
93         reallocateIndexes();
94     }
95
96     public int compareRowsByColumn(int row1, int row2, int column)
97     {
98         Class JavaDoc type = model.getColumnClass(column);
99         TableModel JavaDoc data = model;
100
101         // Check for nulls
102

103         Object JavaDoc o1 = data.getValueAt(row1, column);
104         Object JavaDoc o2 = data.getValueAt(row2, column);
105
106         // If both values are null return 0
107
if (o1 == null && o2 == null) {
108             return 0;
109         }
110         else if (o1 == null) { // Define null less than everything.
111
return -1;
112         }
113         else if (o2 == null) {
114             return 1;
115         }
116
117 /* We copy all returned values from the getValue call in case
118 an optimised model is reusing one object to return many values.
119 The Number subclasses in the JDK are immutable and so will not be used in
120 this way but other subclasses of Number might want to do this to save
121 space and avoid unnecessary heap allocation.
122 */

123         if (type.getSuperclass() == java.lang.Number JavaDoc.class)
124             {
125                 Number JavaDoc n1 = (Number JavaDoc)data.getValueAt(row1, column);
126                 double d1 = n1.doubleValue();
127                 Number JavaDoc n2 = (Number JavaDoc)data.getValueAt(row2, column);
128                 double d2 = n2.doubleValue();
129
130                 if (d1 < d2)
131                     return -1;
132                 else if (d1 > d2)
133                     return 1;
134                 else
135                     return 0;
136             }
137         else if (type == java.util.Date JavaDoc.class)
138             {
139                 Date d1 = (Date)data.getValueAt(row1, column);
140                 long n1 = d1.getTime();
141                 Date d2 = (Date)data.getValueAt(row2, column);
142                 long n2 = d2.getTime();
143
144                 if (n1 < n2)
145                     return -1;
146                 else if (n1 > n2)
147                     return 1;
148                 else return 0;
149             }
150         else if (type == String JavaDoc.class)
151             {
152                 String JavaDoc s1 = (String JavaDoc)data.getValueAt(row1, column);
153                 String JavaDoc s2 = (String JavaDoc)data.getValueAt(row2, column);
154                 int result = s1.compareTo(s2);
155
156                 if (result < 0)
157                     return -1;
158                 else if (result > 0)
159                     return 1;
160                 else return 0;
161             }
162         else if (type == Boolean JavaDoc.class)
163             {
164                 Boolean JavaDoc bool1 = (Boolean JavaDoc)data.getValueAt(row1, column);
165                 boolean b1 = bool1.booleanValue();
166                 Boolean JavaDoc bool2 = (Boolean JavaDoc)data.getValueAt(row2, column);
167                 boolean b2 = bool2.booleanValue();
168
169                 if (b1 == b2)
170                     return 0;
171                 else if (b1) // Define false < true
172
return 1;
173                 else
174                     return -1;
175             }
176         else
177             {
178                 Object JavaDoc v1 = data.getValueAt(row1, column);
179                 String JavaDoc s1 = v1.toString();
180                 Object JavaDoc v2 = data.getValueAt(row2, column);
181                 String JavaDoc s2 = v2.toString();
182                 int result = s1.compareTo(s2);
183
184                 if (result < 0)
185                     return -1;
186                 else if (result > 0)
187                     return 1;
188                 else return 0;
189             }
190     }
191
192     public int compare(int row1, int row2)
193     {
194         compares++;
195         for(int level = 0; level < sortingColumns.size(); level++)
196             {
197                 Integer JavaDoc column = (Integer JavaDoc)sortingColumns.elementAt(level);
198                 int result = compareRowsByColumn(row1, row2, column.intValue());
199                 if (result != 0)
200                     return ascending ? result : -result;
201             }
202         return 0;
203     }
204
205     public void reallocateIndexes()
206     {
207         int rowCount = model.getRowCount();
208
209         // Set up a new array of indexes with the right number of elements
210
// for the new data model.
211
indexes = new int[rowCount];
212
213         // Initialise with the identity mapping.
214
for(int row = 0; row < rowCount; row++)
215             indexes[row] = row;
216     }
217
218     public void tableChanged(TableModelEvent JavaDoc e)
219     {
220     System.out.println("Sorter: tableChanged");
221         reallocateIndexes();
222
223         super.tableChanged(e);
224     }
225
226     public void checkModel()
227     {
228         if (indexes.length != model.getRowCount()) {
229             System.err.println("Sorter not informed of a change in model.");
230         }
231     }
232
233     public void sort(Object JavaDoc sender)
234     {
235         checkModel();
236
237         compares = 0;
238         // n2sort();
239
// qsort(0, indexes.length-1);
240
shuttlesort((int[])indexes.clone(), indexes, 0, indexes.length);
241         System.out.println("Compares: "+compares);
242     }
243
244     public void n2sort() {
245         for(int i = 0; i < getRowCount(); i++) {
246             for(int j = i+1; j < getRowCount(); j++) {
247                 if (compare(indexes[i], indexes[j]) == -1) {
248                     swap(i, j);
249                 }
250             }
251         }
252     }
253
254     // This is a home-grown implementation which we have not had time
255
// to research - it may perform poorly in some circumstances. It
256
// requires twice the space of an in-place algorithm and makes
257
// NlogN assigments shuttling the values between the two
258
// arrays. The number of compares appears to vary between N-1 and
259
// NlogN depending on the initial order but the main reason for
260
// using it here is that, unlike qsort, it is stable.
261
public void shuttlesort(int from[], int to[], int low, int high) {
262         if (high - low < 2) {
263             return;
264         }
265         int middle = (low + high)/2;
266         shuttlesort(to, from, low, middle);
267         shuttlesort(to, from, middle, high);
268
269         int p = low;
270         int q = middle;
271
272         /* This is an optional short-cut; at each recursive call,
273         check to see if the elements in this subset are already
274         ordered. If so, no further comparisons are needed; the
275         sub-array can just be copied. The array must be copied rather
276         than assigned otherwise sister calls in the recursion might
277         get out of sinc. When the number of elements is three they
278         are partitioned so that the first set, [low, mid), has one
279         element and and the second, [mid, high), has two. We skip the
280         optimisation when the number of elements is three or less as
281         the first compare in the normal merge will produce the same
282         sequence of steps. This optimisation seems to be worthwhile
283         for partially ordered lists but some analysis is needed to
284         find out how the performance drops to Nlog(N) as the initial
285         order diminishes - it may drop very quickly. */

286
287         if (high - low >= 4 && compare(from[middle-1], from[middle]) <= 0) {
288             for (int i = low; i < high; i++) {
289                 to[i] = from[i];
290             }
291             return;
292         }
293
294         // A normal merge.
295

296         for(int i = low; i < high; i++) {
297             if (q >= high || (p < middle && compare(from[p], from[q]) <= 0)) {
298                 to[i] = from[p++];
299             }
300             else {
301                 to[i] = from[q++];
302             }
303         }
304     }
305
306     public void swap(int i, int j) {
307         int tmp = indexes[i];
308         indexes[i] = indexes[j];
309         indexes[j] = tmp;
310     }
311
312     // The mapping only affects the contents of the data rows.
313
// Pass all requests to these rows through the mapping array: "indexes".
314

315     public Object JavaDoc getValueAt(int aRow, int aColumn)
316     {
317         checkModel();
318         return model.getValueAt(indexes[aRow], aColumn);
319     }
320
321     public void setValueAt(Object JavaDoc aValue, int aRow, int aColumn)
322     {
323         checkModel();
324         model.setValueAt(aValue, indexes[aRow], aColumn);
325     }
326
327     public void sortByColumn(int column) {
328         sortByColumn(column, true);
329     }
330
331     public void sortByColumn(int column, boolean ascending) {
332         this.ascending = ascending;
333         sortingColumns.removeAllElements();
334         sortingColumns.addElement(new Integer JavaDoc(column));
335         sort(this);
336         super.tableChanged(new TableModelEvent JavaDoc(this));
337     }
338
339     // There is no-where else to put this.
340
// Add a mouse listener to the Table to trigger a table sort
341
// when a column heading is clicked in the JTable.
342
public void addMouseListenerToHeaderInTable(JTable JavaDoc table) {
343         final TableSorter sorter = this;
344         final JTable JavaDoc tableView = table;
345         tableView.setColumnSelectionAllowed(false);
346         MouseAdapter JavaDoc listMouseListener = new MouseAdapter JavaDoc() {
347             public void mouseClicked(MouseEvent JavaDoc e) {
348                 TableColumnModel JavaDoc columnModel = tableView.getColumnModel();
349                 int viewColumn = columnModel.getColumnIndexAtX(e.getX());
350                 int column = tableView.convertColumnIndexToModel(viewColumn);
351                 if(e.getClickCount() == 1 && column != -1) {
352                     System.out.println("Sorting ...");
353                     int shiftPressed = e.getModifiers()&InputEvent.SHIFT_MASK;
354                     boolean ascending = (shiftPressed == 0);
355                     sorter.sortByColumn(column, ascending);
356                 }
357              }
358          };
359         JTableHeader JavaDoc th = tableView.getTableHeader();
360         th.addMouseListener(listMouseListener);
361     }
362
363
364
365 }
366
Popular Tags