version 0.3
[jMoule] / src / TableSorter.java
1 /*
2  * Copyright 2002 Sun Microsystems, Inc. All rights reserved.
3  * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
4  */
5
6 /**
7  * A sorter for TableModels. The sorter has a model (conforming to TableModel) 
8  * and itself implements TableModel. TableSorter does not store or copy 
9  * the data in the TableModel, instead it maintains an array of 
10  * integers which it keeps the same size as the number of rows in its 
11  * model. When the model changes it notifies the sorter that something 
12  * has changed eg. "rowsAdded" so that its internal array of integers 
13  * can be reallocated. As requests are made of the sorter (like 
14  * getValueAt(row, col) it redirects them to its model via the mapping 
15  * array. That way the TableSorter appears to hold another copy of the table 
16  * with the rows in a different order. The sorting algorthm used is stable 
17  * which means that it does not move around rows when its comparison 
18  * function returns 0 to denote that they are equivalent. 
19  *
20  * @version 1.9 02/06/02
21  * @author Philip Milne
22  */
23
24 import java.util.*;
25
26 import javax.swing.table.TableModel;
27 import javax.swing.event.TableModelEvent;
28
29 // Imports for picking up mouse events from the JTable. 
30
31 import java.awt.event.MouseAdapter;
32 import java.awt.event.MouseEvent;
33 import java.awt.event.InputEvent;
34 import javax.swing.JTable;
35 import javax.swing.table.JTableHeader;
36 import javax.swing.table.TableColumn;
37 import javax.swing.table.TableColumnModel;
38
39 public class TableSorter extends TableMap
40 {
41     int             indexes[];
42     Vector          sortingColumns = new Vector();
43     boolean         ascending = true;
44     int compares;
45     int Xcolumn=0;
46     boolean Xascending=false;
47
48     public TableSorter()
49     {
50         indexes = new int[0]; // For consistency.        
51     }
52
53     public TableSorter(TableModel model)
54     {
55         setModel(model);
56     }
57
58     public void setModel(TableModel model) {
59         super.setModel(model); 
60         reallocateIndexes(); 
61     }
62
63     public int compareRowsByColumn(int row1, int row2, int column)
64     {
65         Class type = model.getColumnClass(column);
66         TableModel data = model;
67
68         // Check for nulls
69
70         Object o1 = data.getValueAt(row1, column);
71         Object o2 = data.getValueAt(row2, column); 
72
73         // If both values are null return 0
74         if (o1 == null && o2 == null) {
75             return 0; 
76         }
77         else if (o1 == null) { // Define null less than everything. 
78             return -1; 
79         } 
80         else if (o2 == null) { 
81             return 1; 
82         }
83
84 /* We copy all returned values from the getValue call in case
85 an optimised model is reusing one object to return many values.
86 The Number subclasses in the JDK are immutable and so will not be used in 
87 this way but other subclasses of Number might want to do this to save 
88 space and avoid unnecessary heap allocation. 
89 */
90         if (type.getSuperclass() == java.lang.Number.class)
91             {
92                 Number n1 = (Number)data.getValueAt(row1, column);
93                 double d1 = n1.doubleValue();
94                 Number n2 = (Number)data.getValueAt(row2, column);
95                 double d2 = n2.doubleValue();
96
97                 if (d1 > d2)
98                     return -1;
99                 else if (d1 < d2)
100                     return 1;
101                 else
102                     return 0;
103             }
104         else if (type == java.util.Date.class)
105             {
106                 Date d1 = (Date)data.getValueAt(row1, column);
107                 long n1 = d1.getTime();
108                 Date d2 = (Date)data.getValueAt(row2, column);
109                 long n2 = d2.getTime();
110
111                 if (n1 < n2)
112                     return -1;
113                 else if (n1 > n2)
114                     return 1;
115                 else return 0;
116             }
117         else if (type == String.class)
118             {
119                 String s1 = (String)data.getValueAt(row1, column);
120                 String s2    = (String)data.getValueAt(row2, column);
121                 int result = s1.compareTo(s2);
122
123                 if (result < 0)
124                     return -1;
125                 else if (result > 0)
126                     return 1;
127                 else return 0;
128             }
129         else if (type == Boolean.class)
130             {
131                 Boolean bool1 = (Boolean)data.getValueAt(row1, column);
132                 boolean b1 = bool1.booleanValue();
133                 Boolean bool2 = (Boolean)data.getValueAt(row2, column);
134                 boolean b2 = bool2.booleanValue();
135
136                 if (b1 == b2)
137                     return 0;
138                 else if (b2) // Define false > true
139                     return 1;
140                 else
141                     return -1;
142             }
143         else
144             {
145                 Object v1 = data.getValueAt(row1, column);
146                 String s1 = v1.toString();
147                 Object v2 = data.getValueAt(row2, column);
148                 String s2 = v2.toString();
149                 int result = s1.compareTo(s2);
150
151                 if (result < 0)
152                     return -1;
153                 else if (result > 0)
154                     return 1;
155                 else return 0;
156             }
157     }
158
159     public int compare(int row1, int row2)
160     {
161         compares++;
162         for(int level = 0; level < sortingColumns.size(); level++)
163             {
164                 Integer column = (Integer)sortingColumns.elementAt(level);
165                 int result = compareRowsByColumn(row1, row2, column.intValue());
166                 if (result != 0)
167                     return ascending ? result : -result;
168             }
169         return 0;
170     }
171
172     public void  reallocateIndexes()
173     {
174         int rowCount = model.getRowCount();
175
176         // Set up a new array of indexes with the right number of elements
177         // for the new data model.
178         indexes = new int[rowCount];
179
180         // Initialise with the identity mapping.
181         for(int row = 0; row < rowCount; row++)
182             indexes[row] = row;
183     }
184
185     public void tableChanged(TableModelEvent e)
186     {
187         //System.out.println("Sorter: tableChanged"); 
188         reallocateIndexes();
189
190         sortByColumn(Xcolumn, Xascending); 
191         super.tableChanged(e);
192     }
193
194     public void checkModel()
195     {
196         if (indexes.length != model.getRowCount()) {
197             //System.err.println("Sorter not informed of a change in model.");
198         }
199     }
200
201     public void  sort(Object sender)
202     {
203         checkModel();
204
205         compares = 0;
206         // n2sort();
207         // qsort(0, indexes.length-1);
208         shuttlesort((int[])indexes.clone(), indexes, 0, indexes.length);
209         //System.out.println("Compares: "+compares);
210     }
211
212     public void n2sort() {
213         for(int i = 0; i < getRowCount(); i++) {
214             for(int j = i+1; j < getRowCount(); j++) {
215                 if (compare(indexes[i], indexes[j]) == -1) {
216                     swap(i, j);
217                 }
218             }
219         }
220     }
221
222     // This is a home-grown implementation which we have not had time
223     // to research - it may perform poorly in some circumstances. It
224     // requires twice the space of an in-place algorithm and makes
225     // NlogN assigments shuttling the values between the two
226     // arrays. The number of compares appears to vary between N-1 and
227     // NlogN depending on the initial order but the main reason for
228     // using it here is that, unlike qsort, it is stable.
229     public void shuttlesort(int from[], int to[], int low, int high) {
230         if (high - low < 2) {
231             return;
232         }
233         int middle = (low + high)/2;
234         shuttlesort(to, from, low, middle);
235         shuttlesort(to, from, middle, high);
236
237         int p = low;
238         int q = middle;
239
240         /* This is an optional short-cut; at each recursive call,
241         check to see if the elements in this subset are already
242         ordered.  If so, no further comparisons are needed; the
243         sub-array can just be copied.  The array must be copied rather
244         than assigned otherwise sister calls in the recursion might
245         get out of sinc.  When the number of elements is three they
246         are partitioned so that the first set, [low, mid), has one
247         element and and the second, [mid, high), has two. We skip the
248         optimisation when the number of elements is three or less as
249         the first compare in the normal merge will produce the same
250         sequence of steps. This optimisation seems to be worthwhile
251         for partially ordered lists but some analysis is needed to
252         find out how the performance drops to Nlog(N) as the initial
253         order diminishes - it may drop very quickly.  */
254
255         if (high - low >= 4 && compare(from[middle-1], from[middle]) <= 0) {
256             for (int i = low; i < high; i++) {
257                 to[i] = from[i];
258             }
259             return;
260         }
261
262         // A normal merge. 
263
264         for(int i = low; i < high; i++) {
265             if (q >= high || (p < middle && compare(from[p], from[q]) <= 0)) {
266                 to[i] = from[p++];
267             }
268             else {
269                 to[i] = from[q++];
270             }
271         }
272     }
273
274     public void swap(int i, int j) {
275         int tmp = indexes[i];
276         indexes[i] = indexes[j];
277         indexes[j] = tmp;
278     }
279
280     // The mapping only affects the contents of the data rows.
281     // Pass all requests to these rows through the mapping array: "indexes".
282
283     public Object getValueAt(int aRow, int aColumn)
284     {
285         checkModel();
286         return model.getValueAt(indexes[aRow], aColumn);
287     }
288
289     public void setValueAt(Object aValue, int aRow, int aColumn)
290     {
291         checkModel();
292         model.setValueAt(aValue, indexes[aRow], aColumn);
293     }
294
295     public void sortByColumn(int column) {
296         sortByColumn(column, true);
297     }
298
299     public void sortByColumn(int column, boolean ascending) {
300         this.ascending = ascending;
301         sortingColumns.removeAllElements();
302         sortingColumns.addElement(new Integer(column));
303         sort(this);
304         super.tableChanged(new TableModelEvent(this)); 
305     }
306
307     // There is no-where else to put this. 
308     // Add a mouse listener to the Table to trigger a table sort 
309     // when a column heading is clicked in the JTable. 
310     public void addMouseListenerToHeaderInTable(JTable table) { 
311         final TableSorter sorter = this; 
312         final JTable tableView = table; 
313         tableView.setColumnSelectionAllowed(false); 
314         MouseAdapter listMouseListener = new MouseAdapter() {
315             public void mouseClicked(MouseEvent e) {
316                 TableColumnModel columnModel = tableView.getColumnModel();
317                 int viewColumn = columnModel.getColumnIndexAtX(e.getX()); 
318                 int column = tableView.convertColumnIndexToModel(viewColumn); 
319                 if(e.getClickCount() == 1 && column != -1) {
320                     //System.out.println("Sorting ..."); 
321                     int shiftPressed = e.getModifiers()&InputEvent.SHIFT_MASK; 
322                     boolean ascending = (shiftPressed == 0); 
323                     sorter.sortByColumn(Xcolumn=column, Xascending=ascending); 
324                 }
325              }
326          };
327         JTableHeader th = tableView.getTableHeader(); 
328         th.addMouseListener(listMouseListener); 
329     }
330
331
332
333 }