1 19 20 package org.netbeans.lib.editor.util.swing; 21 22 import java.util.Comparator ; 23 import java.util.List ; 24 import javax.swing.text.BadLocationException ; 25 import javax.swing.text.Document ; 26 import javax.swing.text.Position ; 27 28 37 38 public class PositionRegion { 39 40 41 private static Comparator <PositionRegion> comparator; 42 43 50 public static final Comparator <PositionRegion> getComparator() { 51 if (comparator == null) { 52 comparator = new Comparator <PositionRegion>() { 53 public int compare(PositionRegion pr1, PositionRegion pr2) { 54 return pr1.getStartOffset() - pr2.getStartOffset(); 55 } 56 }; 57 } 58 return comparator; 59 } 60 61 72 public static Position createFixedPosition(final int offset) { 73 if (offset < 0) { 74 throw new IllegalArgumentException ("offset < 0"); 75 } 76 return new Position () { 77 public int getOffset() { 78 return offset; 79 } 80 }; 81 } 82 83 91 public static boolean isRegionsSorted(List <PositionRegion> positionRegionList) { 92 for (int i = positionRegionList.size() - 2; i >= 0; i--) { 93 if (getComparator().compare(positionRegionList.get(i), 94 positionRegionList.get(i + 1)) > 0) { 95 return false; 96 } 97 } 98 return true; 99 } 100 101 private Position startPosition; 102 103 private Position endPosition; 104 105 111 public PositionRegion(Position startPosition, Position endPosition) { 112 assertPositionsValid(startPosition, endPosition); 113 this.startPosition = startPosition; 114 this.endPosition = endPosition; 115 } 116 117 121 public PositionRegion(Document doc, int startOffset, int endOffset) throws BadLocationException { 122 this(doc.createPosition(startOffset), doc.createPosition(endOffset)); 123 } 124 125 130 public final int getStartOffset() { 131 return startPosition.getOffset(); 132 } 133 134 139 public final Position getStartPosition() { 140 return startPosition; 141 } 142 143 148 public final int getEndOffset() { 149 return endPosition.getOffset(); 150 } 151 152 157 public final Position getEndPosition() { 158 return endPosition; 159 } 160 161 167 public final int getLength() { 168 return getEndOffset() - getStartOffset(); 169 } 170 171 175 void resetImpl(Position startPosition, Position endPosition) { 176 assertPositionsValid(startPosition, endPosition); 177 this.startPosition = startPosition; 178 this.endPosition = endPosition; 179 } 180 181 185 void setStartPositionImpl(Position startPosition) { 186 assertPositionsValid(startPosition, endPosition); 187 this.startPosition = startPosition; 188 } 189 190 194 void setEndPositionImpl(Position endPosition) { 195 assertPositionsValid(startPosition, endPosition); 196 this.endPosition = endPosition; 197 } 198 199 private static void assertPositionsValid(Position startPos, Position endPos) { 200 assert (startPos.getOffset() <= endPos.getOffset()) 201 : "startPosition=" + startPos.getOffset() + " > endPosition=" + endPos; 203 } 204 205 } 206 | Popular Tags |