KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > objectweb > mobilitools > util > gui > TableSorter


1 /**
2  * A sorter for TableModels. The sorter has a model (conforming to TableModel)
3  * and itself implements TableModel. TableSorter does not store or copy
4  * the data in the TableModel, instead it maintains an array of
5  * integers which it keeps the same size as the number of rows in its
6  * model. When the model changes it notifies the sorter that something
7  * has changed eg. "rowsAdded" so that its internal array of integers
8  * can be reallocated. As requests are made of the sorter (like
9  * getValueAt(row, col) it redirects them to its model via the mapping
10  * array. That way the TableSorter appears to hold another copy of the table
11  * with the rows in a different order. The sorting algorthm used is stable
12  * which means that it does not move around rows when its comparison
13  * function returns 0 to denote that they are equivalent.
14  *
15  * @version 1.5 12/17/97
16  * @author Philip Milne adapted by Bruno Dillenseger
17  */

18
19 package org.objectweb.mobilitools.util.gui;
20
21 import java.util.*;
22
23 import javax.swing.table.TableModel JavaDoc;
24 import javax.swing.event.TableModelEvent JavaDoc;
25
26 // Imports for picking up mouse events from the JTable.
27

28 import java.awt.event.MouseAdapter JavaDoc;
29 import java.awt.event.MouseEvent JavaDoc;
30 import java.awt.event.InputEvent JavaDoc;
31 import javax.swing.JTable JavaDoc;
32 import javax.swing.table.JTableHeader JavaDoc;
33 import javax.swing.table.TableColumnModel JavaDoc;
34
35 public class TableSorter extends TableMap {
36     int indexes[];
37     Vector sortingColumns = new Vector();
38     boolean ascending = true;
39     int compares;
40     JTable JavaDoc tableView;
41
42     public TableSorter() {
43         indexes = new int[0]; // for consistency
44
}
45
46     public TableSorter(TableModel JavaDoc model) {
47         setModel(model);
48     }
49
50     public void setModel(TableModel JavaDoc model) {
51         super.setModel(model);
52         reallocateIndexes();
53     }
54
55     synchronized public int compareRowsByColumn(int row1, int row2, int column) {
56         Class JavaDoc type = model.getColumnClass(column);
57         TableModel JavaDoc data = model;
58
59         // Check for nulls.
60

61         Object JavaDoc o1 = data.getValueAt(row1, column);
62         Object JavaDoc o2 = data.getValueAt(row2, column);
63
64         // If both values are null, return 0.
65
if (o1 == null && o2 == null) {
66             return 0;
67         } else if (o1 == null) { // Define null less than everything.
68
return -1;
69         } else if (o2 == null) {
70             return 1;
71         }
72
73         /*
74          * We copy all returned values from the getValue call in case
75          * an optimised model is reusing one object to return many
76          * values. The Number subclasses in the JDK are immutable and
77          * so will not be used in this way but other subclasses of
78          * Number might want to do this to save space and avoid
79          * unnecessary heap allocation.
80          */

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

240
241         if (high - low >= 4 && compare(from[middle-1], from[middle]) <= 0) {
242             for (int i = low; i < high; i++) {
243                 to[i] = from[i];
244             }
245             return;
246         }
247
248         // A normal merge.
249

250         for (int i = low; i < high; i++) {
251             if (q >= high || (p < middle && compare(from[p], from[q]) <= 0)) {
252                 to[i] = from[p++];
253             }
254             else {
255                 to[i] = from[q++];
256             }
257         }
258     }
259
260     public void swap(int i, int j) {
261         int tmp = indexes[i];
262         indexes[i] = indexes[j];
263         indexes[j] = tmp;
264     }
265
266     // The mapping only affects the contents of the data rows.
267
// Pass all requests to these rows through the mapping array: "indexes".
268

269     synchronized public Object JavaDoc getValueAt(int aRow, int aColumn) {
270         checkModel();
271         return model.getValueAt(indexes[aRow], aColumn);
272     }
273
274     synchronized public void setValueAt(Object JavaDoc aValue, int aRow, int aColumn) {
275         checkModel();
276         model.setValueAt(aValue, indexes[aRow], aColumn);
277     }
278
279     public void sortByColumn(int column) {
280         sortByColumn(column, true);
281     }
282
283     synchronized public void sortByColumn(int column, boolean ascending) {
284         this.ascending = ascending;
285         sortingColumns.removeAllElements();
286         sortingColumns.addElement(new Integer JavaDoc(column));
287         sort(this);
288         super.tableChanged(new TableModelEvent JavaDoc(this));
289     }
290
291     // There is no-where else to put this.
292
// Add a mouse listener to the Table to trigger a table sort
293
// when a column heading is clicked in the JTable.
294
public void addMouseListenerToHeaderInTable(JTable JavaDoc table) {
295         final TableSorter sorter = this;
296         tableView = table;
297         tableView.setColumnSelectionAllowed(false);
298         MouseAdapter JavaDoc listMouseListener = new MouseAdapter JavaDoc() {
299             public void mouseClicked(MouseEvent JavaDoc e) {
300                 TableColumnModel JavaDoc columnModel = tableView.getColumnModel();
301                 int viewColumn = columnModel.getColumnIndexAtX(e.getX());
302                 int column = tableView.convertColumnIndexToModel(viewColumn);
303                 if (e.getClickCount() == 1 && column != -1) {
304                     int shiftPressed = e.getModifiers()&InputEvent.SHIFT_MASK;
305                     boolean ascending = (shiftPressed == 0);
306                     sorter.sortByColumn(column, ascending);
307                     TableSorter.this.tableView.clearSelection();
308                 }
309             }
310         };
311         JTableHeader JavaDoc th = tableView.getTableHeader();
312         th.addMouseListener(listMouseListener);
313     }
314 }
315
Popular Tags