2 * Copyright 2002 Sun Microsystems, Inc. All rights reserved.
3 * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
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.
20 * @version 1.9 02/06/02
21 * @author Philip Milne
26 import javax.swing.table.TableModel;
27 import javax.swing.event.TableModelEvent;
29 // Imports for picking up mouse events from the JTable.
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;
39 public class TableSorter extends TableMap
42 Vector sortingColumns = new Vector();
43 boolean ascending = true;
46 boolean Xascending=false;
50 indexes = new int[0]; // For consistency.
53 public TableSorter(TableModel model)
58 public void setModel(TableModel model) {
59 super.setModel(model);
63 public int compareRowsByColumn(int row1, int row2, int column)
65 Class type = model.getColumnClass(column);
66 TableModel data = model;
70 Object o1 = data.getValueAt(row1, column);
71 Object o2 = data.getValueAt(row2, column);
73 // If both values are null return 0
74 if (o1 == null && o2 == null) {
77 else if (o1 == null) { // Define null less than everything.
80 else if (o2 == null) {
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.
90 if (type.getSuperclass() == java.lang.Number.class)
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();
104 else if (type == java.util.Date.class)
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();
117 else if (type == String.class)
119 String s1 = (String)data.getValueAt(row1, column);
120 String s2 = (String)data.getValueAt(row2, column);
121 int result = s1.compareTo(s2);
129 else if (type == Boolean.class)
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();
138 else if (b2) // Define false > true
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);
159 public int compare(int row1, int row2)
162 for(int level = 0; level < sortingColumns.size(); level++)
164 Integer column = (Integer)sortingColumns.elementAt(level);
165 int result = compareRowsByColumn(row1, row2, column.intValue());
167 return ascending ? result : -result;
172 public void reallocateIndexes()
174 int rowCount = model.getRowCount();
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];
180 // Initialise with the identity mapping.
181 for(int row = 0; row < rowCount; row++)
185 public void tableChanged(TableModelEvent e)
187 //System.out.println("Sorter: tableChanged");
190 sortByColumn(Xcolumn, Xascending);
191 super.tableChanged(e);
194 public void checkModel()
196 if (indexes.length != model.getRowCount()) {
197 //System.err.println("Sorter not informed of a change in model.");
201 public void sort(Object sender)
207 // qsort(0, indexes.length-1);
208 shuttlesort((int[])indexes.clone(), indexes, 0, indexes.length);
209 //System.out.println("Compares: "+compares);
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) {
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) {
233 int middle = (low + high)/2;
234 shuttlesort(to, from, low, middle);
235 shuttlesort(to, from, middle, high);
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. */
255 if (high - low >= 4 && compare(from[middle-1], from[middle]) <= 0) {
256 for (int i = low; i < high; i++) {
264 for(int i = low; i < high; i++) {
265 if (q >= high || (p < middle && compare(from[p], from[q]) <= 0)) {
274 public void swap(int i, int j) {
275 int tmp = indexes[i];
276 indexes[i] = indexes[j];
280 // The mapping only affects the contents of the data rows.
281 // Pass all requests to these rows through the mapping array: "indexes".
283 public Object getValueAt(int aRow, int aColumn)
286 return model.getValueAt(indexes[aRow], aColumn);
289 public void setValueAt(Object aValue, int aRow, int aColumn)
292 model.setValueAt(aValue, indexes[aRow], aColumn);
295 public void sortByColumn(int column) {
296 sortByColumn(column, true);
299 public void sortByColumn(int column, boolean ascending) {
300 this.ascending = ascending;
301 sortingColumns.removeAllElements();
302 sortingColumns.addElement(new Integer(column));
304 super.tableChanged(new TableModelEvent(this));
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);
327 JTableHeader th = tableView.getTableHeader();
328 th.addMouseListener(listMouseListener);