Path: blob/master/src/demo/share/jfc/TableExample/TableSorter.java
41152 views
/*1* Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.2*3* Redistribution and use in source and binary forms, with or without4* modification, are permitted provided that the following conditions5* are met:6*7* - Redistributions of source code must retain the above copyright8* notice, this list of conditions and the following disclaimer.9*10* - Redistributions in binary form must reproduce the above copyright11* notice, this list of conditions and the following disclaimer in the12* documentation and/or other materials provided with the distribution.13*14* - Neither the name of Oracle nor the names of its15* contributors may be used to endorse or promote products derived16* from this software without specific prior written permission.17*18* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS19* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,20* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR21* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR22* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,23* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,24* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR25* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF26* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING27* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS28* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.29*/3031/*32* This source code is provided to illustrate the usage of a given feature33* or technique and has been deliberately simplified. Additional steps34* required for a production-quality application, such as security checks,35* input validation and proper error handling, might not be present in36* this sample code.37*/38394041import javax.swing.table.TableModel;42import javax.swing.event.TableModelEvent;43import java.awt.event.MouseAdapter;44import java.awt.event.MouseEvent;45import java.awt.event.InputEvent;46import java.util.ArrayList;47import java.util.Date;48import java.util.List;49import javax.swing.JTable;50import javax.swing.table.JTableHeader;51import javax.swing.table.TableColumnModel;525354/**55* A sorter for TableModels. The sorter has a model (conforming to TableModel)56* and itself implements TableModel. TableSorter does not store or copy57* the data in the TableModel, instead it maintains an array of58* integers which it keeps the same size as the number of rows in its59* model. When the model changes it notifies the sorter that something60* has changed eg. "rowsAdded" so that its internal array of integers61* can be reallocated. As requests are made of the sorter (like62* getValueAt(row, col) it redirects them to its model via the mapping63* array. That way the TableSorter appears to hold another copy of the table64* with the rows in a different order. The sorting algorthm used is stable65* which means that it does not move around rows when its comparison66* function returns 0 to denote that they are equivalent.67*68* @author Philip Milne69*/70@SuppressWarnings("serial")71public final class TableSorter extends TableMap {7273int[] indexes;74List<Integer> sortingColumns = new ArrayList<Integer>();75boolean ascending = true;76int compares;7778public TableSorter() {79indexes = new int[0]; // For consistency.80}8182public TableSorter(TableModel model) {83setModel(model);84}8586@Override87public void setModel(TableModel model) {88super.setModel(model);89reallocateIndexes();90}9192public int compareRowsByColumn(int row1, int row2, int column) {93Class<?> type = model.getColumnClass(column);94TableModel data = model;9596// Check for nulls9798Object o1 = data.getValueAt(row1, column);99Object o2 = data.getValueAt(row2, column);100101// If both values are null return 0102if (o1 == null && o2 == null) {103return 0;104} else if (o1 == null) { // Define null less than everything.105return -1;106} else if (o2 == null) {107return 1;108}109110/* We copy all returned values from the getValue call in case111an optimised model is reusing one object to return many values.112The Number subclasses in the JDK are immutable and so will not be used113in this way but other subclasses of Number might want to do this to save114space and avoid unnecessary heap allocation.115*/116if (type.getSuperclass() == java.lang.Number.class) {117Number n1 = (Number) data.getValueAt(row1, column);118double d1 = n1.doubleValue();119Number n2 = (Number) data.getValueAt(row2, column);120double d2 = n2.doubleValue();121122if (d1 < d2) {123return -1;124} else if (d1 > d2) {125return 1;126} else {127return 0;128}129} else if (type == java.util.Date.class) {130Date d1 = (Date) data.getValueAt(row1, column);131long n1 = d1.getTime();132Date d2 = (Date) data.getValueAt(row2, column);133long n2 = d2.getTime();134135if (n1 < n2) {136return -1;137} else if (n1 > n2) {138return 1;139} else {140return 0;141}142} else if (type == String.class) {143String s1 = (String) data.getValueAt(row1, column);144String s2 = (String) data.getValueAt(row2, column);145int result = s1.compareTo(s2);146147if (result < 0) {148return -1;149} else if (result > 0) {150return 1;151} else {152return 0;153}154} else if (type == Boolean.class) {155Boolean bool1 = (Boolean) data.getValueAt(row1, column);156boolean b1 = bool1.booleanValue();157Boolean bool2 = (Boolean) data.getValueAt(row2, column);158boolean b2 = bool2.booleanValue();159160if (b1 == b2) {161return 0;162} else if (b1) // Define false < true163{164return 1;165} else {166return -1;167}168} else {169Object v1 = data.getValueAt(row1, column);170String s1 = v1.toString();171Object v2 = data.getValueAt(row2, column);172String s2 = v2.toString();173int result = s1.compareTo(s2);174175if (result < 0) {176return -1;177} else if (result > 0) {178return 1;179} else {180return 0;181}182}183}184185public int compare(int row1, int row2) {186compares++;187for (int level = 0; level < sortingColumns.size(); level++) {188Integer column = sortingColumns.get(level);189int result = compareRowsByColumn(row1, row2, column.intValue());190if (result != 0) {191return ascending ? result : -result;192}193}194return 0;195}196197public void reallocateIndexes() {198int rowCount = model.getRowCount();199200// Set up a new array of indexes with the right number of elements201// for the new data model.202indexes = new int[rowCount];203204// Initialise with the identity mapping.205for (int row = 0; row < rowCount; row++) {206indexes[row] = row;207}208}209210@Override211public void tableChanged(TableModelEvent e) {212System.out.println("Sorter: tableChanged");213reallocateIndexes();214215super.tableChanged(e);216}217218public void checkModel() {219if (indexes.length != model.getRowCount()) {220System.err.println("Sorter not informed of a change in model.");221}222}223224public void sort(Object sender) {225checkModel();226227compares = 0;228// n2sort();229// qsort(0, indexes.length-1);230shuttlesort(indexes.clone(), indexes, 0, indexes.length);231System.out.println("Compares: " + compares);232}233234public void n2sort() {235for (int i = 0; i < getRowCount(); i++) {236for (int j = i + 1; j < getRowCount(); j++) {237if (compare(indexes[i], indexes[j]) == -1) {238swap(i, j);239}240}241}242}243244// This is a home-grown implementation which we have not had time245// to research - it may perform poorly in some circumstances. It246// requires twice the space of an in-place algorithm and makes247// NlogN assigments shuttling the values between the two248// arrays. The number of compares appears to vary between N-1 and249// NlogN depending on the initial order but the main reason for250// using it here is that, unlike qsort, it is stable.251public void shuttlesort(int[] from, int[] to, int low, int high) {252if (high - low < 2) {253return;254}255int middle = (low + high) / 2;256shuttlesort(to, from, low, middle);257shuttlesort(to, from, middle, high);258259int p = low;260int q = middle;261262/* This is an optional short-cut; at each recursive call,263check to see if the elements in this subset are already264ordered. If so, no further comparisons are needed; the265sub-array can just be copied. The array must be copied rather266than assigned otherwise sister calls in the recursion might267get out of sinc. When the number of elements is three they268are partitioned so that the first set, [low, mid), has one269element and the second, [mid, high), has two. We skip the270optimisation when the number of elements is three or less as271the first compare in the normal merge will produce the same272sequence of steps. This optimisation seems to be worthwhile273for partially ordered lists but some analysis is needed to274find out how the performance drops to Nlog(N) as the initial275order diminishes - it may drop very quickly. */276277if (high - low >= 4 && compare(from[middle - 1], from[middle]) <= 0) {278System.arraycopy(from, low, to, low, high - low);279return;280}281282// A normal merge.283284for (int i = low; i < high; i++) {285if (q >= high || (p < middle && compare(from[p], from[q]) <= 0)) {286to[i] = from[p++];287} else {288to[i] = from[q++];289}290}291}292293public void swap(int i, int j) {294int tmp = indexes[i];295indexes[i] = indexes[j];296indexes[j] = tmp;297}298299// The mapping only affects the contents of the data rows.300// Pass all requests to these rows through the mapping array: "indexes".301@Override302public Object getValueAt(int aRow, int aColumn) {303checkModel();304return model.getValueAt(indexes[aRow], aColumn);305}306307@Override308public void setValueAt(Object aValue, int aRow, int aColumn) {309checkModel();310model.setValueAt(aValue, indexes[aRow], aColumn);311}312313public void sortByColumn(int column) {314sortByColumn(column, true);315}316317public void sortByColumn(int column, boolean ascending) {318this.ascending = ascending;319sortingColumns.clear();320sortingColumns.add(column);321sort(this);322super.tableChanged(new TableModelEvent(this));323}324325// There is no-where else to put this.326// Add a mouse listener to the Table to trigger a table sort327// when a column heading is clicked in the JTable.328public void addMouseListenerToHeaderInTable(JTable table) {329final TableSorter sorter = this;330final JTable tableView = table;331tableView.setColumnSelectionAllowed(false);332MouseAdapter listMouseListener = new MouseAdapter() {333334@Override335public void mouseClicked(MouseEvent e) {336TableColumnModel columnModel = tableView.getColumnModel();337int viewColumn = columnModel.getColumnIndexAtX(e.getX());338int column = tableView.convertColumnIndexToModel(viewColumn);339if (e.getClickCount() == 1 && column != -1) {340System.out.println("Sorting ...");341int shiftPressed = e.getModifiersEx() & InputEvent.SHIFT_DOWN_MASK;342boolean ascending = (shiftPressed == 0);343sorter.sortByColumn(column, ascending);344}345}346};347JTableHeader th = tableView.getTableHeader();348th.addMouseListener(listMouseListener);349}350}351352353