Index: javax/swing/text/AbstractDocument.java =================================================================== RCS file: /cvsroot/classpath/classpath/javax/swing/text/AbstractDocument.java,v retrieving revision 1.29 diff -u -r1.29 AbstractDocument.java --- javax/swing/text/AbstractDocument.java 28 Sep 2005 19:40:43 -0000 1.29 +++ javax/swing/text/AbstractDocument.java 28 Sep 2005 20:07:34 -0000 @@ -1519,19 +1519,30 @@ */ public int getElementIndex(int offset) { - // If we have no children, return -1. - if (getElementCount() == 0) - return - 1; - + // If offset is less than the start offset of our first child, + // return 0 + if (offset < getStartOffset()) + return 0; + // XXX: There is surely a better algorithm // as beginning from first element each time. - for (int index = 0; index < children.length; ++index) + for (int index = 0; index < children.length - 1; ++index) { Element elem = children[index]; if ((elem.getStartOffset() <= offset) && (offset < elem.getEndOffset())) return index; + // If the next element's start offset is greater than offset + // then we have to return the closest Element, since no Elements + // will contain the offset + if (children[index + 1].getStartOffset() > offset) + { + if ((offset - elem.getEndOffset()) > (children[index + 1].getStartOffset() - offset)) + return index + 1; + else + return index; + } } // If offset is greater than the index of the last element, return