1 7 package javax.swing; 8 9 import java.util.Comparator ; 10 import java.util.LinkedList ; 11 import java.util.ListIterator ; 12 import java.awt.Component ; 13 import java.awt.ComponentOrientation ; 14 import java.awt.Window ; 15 16 17 25 final class LayoutComparator implements Comparator , java.io.Serializable { 26 27 private static final int ROW_TOLERANCE = 10; 28 29 private boolean horizontal = true; 30 private boolean leftToRight = true; 31 32 void setComponentOrientation(ComponentOrientation orientation) { 33 horizontal = orientation.isHorizontal(); 34 leftToRight = orientation.isLeftToRight(); 35 } 36 37 public int compare(Object o1, Object o2) { 38 Component a = (Component )o1; 39 Component b = (Component )o2; 40 41 if (a == b) { 42 return 0; 43 } 44 45 if (a.getParent() != b.getParent()) { 51 LinkedList aAncestory, bAncestory; 52 53 for(aAncestory = new LinkedList (); a != null; a = a.getParent()) { 54 aAncestory.add(a); 55 if (a instanceof Window ) { 56 break; 57 } 58 } 59 if (a == null) { 60 throw new ClassCastException (); 62 } 63 64 for(bAncestory = new LinkedList (); b != null; b = b.getParent()) { 65 bAncestory.add(b); 66 if (b instanceof Window ) { 67 break; 68 } 69 } 70 if (b == null) { 71 throw new ClassCastException (); 73 } 74 75 for (ListIterator 76 aIter = aAncestory.listIterator(aAncestory.size()), 77 bIter = bAncestory.listIterator(bAncestory.size()); ;) { 78 if (aIter.hasPrevious()) { 79 a = (Component )aIter.previous(); 80 } else { 81 return -1; 83 } 84 85 if (bIter.hasPrevious()) { 86 b = (Component )bIter.previous(); 87 } else { 88 return 1; 90 } 91 92 if (a != b) { 93 break; 94 } 95 } 96 } 97 98 int ax = a.getX(), ay = a.getY(), bx = b.getX(), by = b.getY(); 99 100 int zOrder = a.getParent().getComponentZOrder(a) - b.getParent().getComponentZOrder(b); 101 if (horizontal) { 102 if (leftToRight) { 103 104 106 if (Math.abs(ay - by) < ROW_TOLERANCE) { 107 return (ax < bx) ? -1 : ((ax > bx) ? 1 : zOrder); 108 } else { 109 return (ay < by) ? -1 : 1; 110 } 111 } else { 113 115 if (Math.abs(ay - by) < ROW_TOLERANCE) { 116 return (ax > bx) ? -1 : ((ax < bx) ? 1 : zOrder); 117 } else { 118 return (ay < by) ? -1 : 1; 119 } 120 } 121 } else { if (leftToRight) { 123 124 126 if (Math.abs(ax - bx) < ROW_TOLERANCE) { 127 return (ay < by) ? -1 : ((ay > by) ? 1 : zOrder); 128 } else { 129 return (ax < bx) ? -1 : 1; 130 } 131 } else { 133 135 if (Math.abs(ax - bx) < ROW_TOLERANCE) { 136 return (ay < by) ? -1 : ((ay > by) ? 1 : zOrder); 137 } else { 138 return (ax > bx) ? -1 : 1; 139 } 140 } 141 } 142 } 143 } 144 | Popular Tags |