home *** CD-ROM | disk | FTP | other *** search
/ Programming Languages Suite / JBuilder8.iso / Solaris / resource / jre / demo / jfc / TableExample / src / TableSorter.java < prev   
Encoding:
Java Source  |  2002-09-06  |  12.6 KB  |  365 lines

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