KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > ca > commons > cbutil > CBTableSorter


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

21
22 import javax.swing.*;
23 import javax.swing.event.TableModelEvent JavaDoc;
24 import javax.swing.table.*;
25 import java.awt.event.*;
26 import java.util.Date JavaDoc;
27 import java.util.Vector JavaDoc;
28
29 public class CBTableSorter extends CBTableMap
30 {
31     int indexes[];
32     Vector JavaDoc sortingColumns = new Vector JavaDoc();
33     boolean ascending = true;
34     int compares;
35
36     public CBTableSorter()
37     {
38         indexes = new int[0]; // for consistency
39
}
40
41     public CBTableSorter(TableModel model)
42     {
43         setModel(model);
44     }
45
46
47     /**
48      * Takes the <i>sorted</i> row position, and returns the
49      * real row position in the original table model.
50      */

51
52     public int getTrueIndex(int i)
53     {
54         return indexes[i];
55     }
56
57     public void setModel(TableModel model)
58     {
59         super.setModel(model);
60         reallocateIndexes();
61     }
62
63     public int compareRowsByColumn(int row1, int row2, int column)
64     {
65         Class JavaDoc type = model.getColumnClass(column);
66         TableModel data = model;
67
68         // Check for nulls.
69

70         Object JavaDoc o1 = data.getValueAt(row1, column);
71         Object JavaDoc o2 = data.getValueAt(row2, column);
72
73         // If both values are null, return 0.
74
if (o1 == null && o2 == null)
75         {
76             return 0;
77         }
78         else if (o1 == null)
79         { // Define null less than everything.
80
return -1;
81         }
82         else if (o2 == null)
83         {
84             return 1;
85         }
86
87         /*
88          * We copy all returned values from the getValue call in case
89          * an optimised model is reusing one object to return many
90          * values. The Number subclasses in the JDK are immutable and
91          * so will not be used in this way but other subclasses of
92          * Number might want to do this to save space and avoid
93          * unnecessary heap allocation.
94          */

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

303
304         if (high - low >= 4 && compare(from[middle - 1], from[middle]) <= 0)
305         {
306             for (int i = low; i < high; i++)
307             {
308                 to[i] = from[i];
309             }
310             return;
311         }
312
313         // A normal merge.
314

315         for (int i = low; i < high; i++)
316         {
317             if (q >= high || (p < middle && compare(from[p], from[q]) <= 0))
318             {
319                 to[i] = from[p++];
320             }
321             else
322             {
323                 to[i] = from[q++];
324             }
325         }
326     }
327
328     public void swap(int i, int j)
329     {
330         int tmp = indexes[i];
331         indexes[i] = indexes[j];
332         indexes[j] = tmp;
333     }
334
335     // The mapping only affects the contents of the data rows.
336
// Pass all requests to these rows through the mapping array: "indexes".
337

338     public Object JavaDoc getValueAt(int aRow, int aColumn)
339     {
340         checkModel();
341         return model.getValueAt(indexes[aRow], aColumn);
342     }
343
344     public void setValueAt(Object JavaDoc aValue, int aRow, int aColumn)
345     {
346         checkModel();
347         model.setValueAt(aValue, indexes[aRow], aColumn);
348     }
349
350     public void sortByColumn(int column)
351     {
352         sortByColumn(column, true);
353     }
354
355     public void sortByColumn(int column, boolean ascending)
356     {
357         this.ascending = ascending;
358         sortingColumns.removeAllElements();
359         sortingColumns.addElement(new Integer JavaDoc(column));
360         sort(this);
361         super.tableChanged(new TableModelEvent JavaDoc(this));
362     }
363
364     // There is no-where else to put this.
365
// Add a mouse listener to the Table to trigger a table sort
366
// when a column heading is clicked in the JTable.
367
public void addMouseListenerToHeaderInTable(JTable table)
368     {
369         final CBTableSorter sorter = this;
370         final JTable tableView = table;
371         tableView.setColumnSelectionAllowed(false);
372         MouseAdapter listMouseListener = new MouseAdapter()
373         {
374             public void mouseClicked(MouseEvent e)
375             {
376                 TableColumnModel columnModel = tableView.getColumnModel();
377                 int viewColumn = columnModel.getColumnIndexAtX(e.getX());
378                 int column = tableView.convertColumnIndexToModel(viewColumn);
379                 if (e.getClickCount() == 1 && column != -1)
380                 {
381                     //System.out.println("Sorting ...");
382
int shiftPressed = e.getModifiers() & InputEvent.SHIFT_MASK;
383                     boolean ascending = (shiftPressed == 0);
384                     sorter.sortByColumn(column, ascending);
385                 }
386             }
387         };
388         JTableHeader th = tableView.getTableHeader();
389         th.addMouseListener(listMouseListener);
390     }
391 }
392
Popular Tags