1 7 8 package org.jdesktop.swing.decorator; 9 10 15 public abstract class Sorter extends Filter { 16 private boolean ascending = true; 17 18 public Sorter() { 19 this(0, true); 20 } 21 22 public Sorter(int col, boolean ascending) { 23 super(col); 24 setAscending(ascending); 25 } 26 27 37 38 43 protected abstract void adopt(Sorter oldSorter); 44 45 56 public void interpose(FilterPipeline filters, ComponentAdapter adapter, 57 Sorter oldSorter) { 58 if (filters != null) { 59 filters.setSorter(this); 60 } 61 adopt(oldSorter); 62 assign(filters); 63 assign(adapter); 64 refresh(oldSorter == null); 65 } 66 67 68 public int compare(int row1, int row2) { 69 int result = compare(row1, row2, getColumnIndex()); 70 return ascending ? result : -result; 71 } 72 73 76 77 private int compare(int row1, int row2, int col) { 78 Object o1 = getInputValue(row1, col); 79 Object o2 = getInputValue(row2, col); 80 81 if (o1 == null && o2 == null) { 83 return 0; 84 } 85 else if (o1 == null) { return -1; 87 } 88 else if (o2 == null) { 89 return 1; 90 } 91 92 if (o1 instanceof Comparable ) { 93 Comparable c1 = (Comparable ) o1; 94 Comparable c2 = (Comparable ) o2; 95 return c1.compareTo(c2); 96 } 97 else if (o1 instanceof Boolean ) { 98 try { 99 Boolean bool1 = (Boolean ) o1; 100 boolean b1 = bool1.booleanValue(); 101 Boolean bool2 = (Boolean ) o2; 102 boolean b2 = bool2.booleanValue(); 103 104 if (b1 == b2) { 105 return 0; 106 } 107 else if (b1) { return 1; 109 } 110 else { 111 return -1; 112 } 113 } 114 catch (ClassCastException ex) { 115 System.out.println("Column class mismatch: " + o1.getClass() + 116 " can't be compared to " + o2.getClass()); 117 } 118 } 119 else { 120 return o1.toString().compareTo(o2.toString()); 121 } 122 123 return 0; 124 } 125 126 public boolean isAscending() { 127 return ascending; 128 } 129 130 public void setAscending(boolean ascending) { 131 this.ascending = ascending; 132 refresh(); 133 } 134 135 public void toggle() { 136 ascending = !ascending; 137 refresh(); 138 } 139 140 } | Popular Tags |