javax.swing.text.Element#getStartOffset ( )源码实例Demo

下面列出了javax.swing.text.Element#getStartOffset ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: MogwaiERDesignerNG   文件: SQLSyntaxDocument.java
@Override
public void remove(int offset, int length) throws BadLocationException {
	int former_line_count = root.getElementCount(); // the number of lines before the insertion

	// delete:
	super.remove(offset, length);

	Element line = root.getElement(root.getElementIndex(offset)); // line where deletion started
	int scan_begin = line.getStartOffset(); // start scanning at the boln of first affected line
	int scan_end = line.getEndOffset() - 1; // end scanning at the eoln of last affected line (after deleteion)
	int line_count = root.getElementCount(); // the number of lines after the insertion
	int first_line = root.getElementIndex(scan_begin); // the first affected line index
	int lines_deleted = former_line_count - line_count; // the number of inserted eolns

	// one or more eolns were deleted:
	if (lines_deleted > 0)
		lineToks.unshift(first_line, lines_deleted);

	// highlight:
	HighlightAffectedText(scan_begin, scan_end, offset, first_line);
}
 
源代码2 项目: netbeans   文件: PUCompletionProvider.java
static int getRowFirstNonWhite(StyledDocument doc, int offset)
        throws BadLocationException {
    Element lineElement = doc.getParagraphElement(offset);
    int start = lineElement.getStartOffset();
    while (start + 1 < lineElement.getEndOffset()) {
        try {
            if (doc.getText(start, 1).charAt(0) != ' ') {
                break;
            }
        } catch (BadLocationException ex) {
            throw (BadLocationException) new BadLocationException(
                    "calling getText(" + start + ", " + (start + 1)
                    + ") on doc of length: " + doc.getLength(), start).initCause(ex);
        }
        start++;
    }
    return start;
}
 
源代码3 项目: rapidminer-studio   文件: SyntaxDocument.java
/**
 * Reparses the document, by passing the specified lines to the token marker. This should be
 * called after a large quantity of text is first inserted.
 * 
 * @param start
 *            The first line to parse
 * @param len
 *            The number of lines, after the first one to parse
 */
public void tokenizeLines(int start, int len) {
	if (tokenMarker == null || !tokenMarker.supportsMultilineTokens()) {
		return;
	}

	Segment lineSegment = new Segment();
	Element map = getDefaultRootElement();

	len += start;

	try {
		for (int i = start; i < len; i++) {
			Element lineElement = map.getElement(i);
			int lineStart = lineElement.getStartOffset();
			getText(lineStart, lineElement.getEndOffset() - lineStart - 1, lineSegment);
			tokenMarker.markTokens(lineSegment, i);
		}
	} catch (BadLocationException bl) {
		bl.printStackTrace();
	}
}
 
源代码4 项目: SikuliX1   文件: PythonIndentation.java
@Override
public String getLeadingWhitespace(StyledDocument doc, int head, int len) throws BadLocationException {
  String ret = "";
  int pos = head;
  while (pos < head + len) {
    Element e = doc.getCharacterElement(pos);
    if (e.getName().equals(StyleConstants.ComponentElementName)) {
      break;
    }
    int eStart = e.getStartOffset();
    int eEnd = e.getEndOffset();
    String space = getLeadingWhitespace(doc.getText(eStart, eEnd - eStart));
    ret += space;
    if (space.length() < eEnd - eStart) {
      break;
    }
    pos = eEnd;
  }
  return ret;
}
 
源代码5 项目: rapidminer-studio   文件: JEditTextArea.java
/**
 * Returns the offset where the selection ends on the specified line.
 */
public int getSelectionEnd(int line) {
	if (line == selectionEndLine) {
		return selectionEnd;
	} else if (rectSelect) {
		Element map = document.getDefaultRootElement();
		int end = selectionEnd - map.getElement(selectionEndLine).getStartOffset();

		Element lineElement = map.getElement(line);
		int lineStart = lineElement.getStartOffset();
		int lineEnd = lineElement.getEndOffset() - 1;
		return Math.min(lineEnd, lineStart + end);
	} else {
		return getLineEndOffset(line) - 1;
	}
}
 
源代码6 项目: desktopclient-java   文件: LinkUtils.java
@Override
public void mouseClicked(MouseEvent e) {
    WebTextPane textPane = (WebTextPane) e.getComponent();
    StyledDocument doc = textPane.getStyledDocument();
    Element elem = doc.getCharacterElement(textPane.viewToModel(e.getPoint()));
    if (!elem.getAttributes().isDefined(URL_ATT_NAME))
        // not a link
        return;

    int len = elem.getEndOffset() - elem.getStartOffset();
    final String url;
    try {
        url = doc.getText(elem.getStartOffset(), len);
    } catch (BadLocationException ex) {
        LOGGER.log(Level.WARNING, "can't get URL", ex);
        return;
    }

    Runnable run = new Runnable() {
        @Override
        public void run() {
            WebUtils.browseSiteSafely(fixProto(url));
        }
    };
    new Thread(run, "Link Browser").start();
}
 
源代码7 项目: visualvm   文件: SyntaxDocument.java
/**
 * Helper method to get the length of an element and avoid getting
 * a too long element at the end of the document
 * @param e
 * @return
 */
private int getElementLength(Element e) {
    int end = e.getEndOffset();
    if (end >= (getLength() - 1)) {
        end--;
    }
    return end - e.getStartOffset();
}
 
源代码8 项目: netbeans   文件: ToolTipAnnotation.java
private static String getIdentifier(final StyledDocument doc, final JEditorPane ep, final int offset) {
    String t = null;
    if (ep.getCaret() != null) { // #255228
        if ((ep.getSelectionStart() <= offset) && (offset <= ep.getSelectionEnd())) {
            t = ep.getSelectedText();
        }
        if (t != null) {
            return t;
        }
    }
    int line = NbDocument.findLineNumber(doc, offset);
    int col = NbDocument.findLineColumn(doc, offset);
    Element lineElem = NbDocument.findLineRootElement(doc).getElement(line);
    try {
        if (lineElem == null) {
            return null;
        }
        int lineStartOffset = lineElem.getStartOffset();
        int lineLen = lineElem.getEndOffset() - lineStartOffset;
        if (col + 1 >= lineLen) {
            // do not evaluate when mouse hover behind the end of line (112662)
            return null;
        }
        t = doc.getText(lineStartOffset, lineLen);
        return getExpressionToEvaluate(t, col);
    } catch (BadLocationException e) {
        return null;
    }
}
 
源代码9 项目: openjdk-jdk8u-backup   文件: bug6857057.java
bug6857057() {
    Element elem = new StubBranchElement(" G L Y P H V");
    GlyphView view = new GlyphView(elem);
    float pos = elem.getStartOffset();
    float len = elem.getEndOffset() - pos;
    int res = view.getBreakWeight(View.X_AXIS, pos, len);
    if (res != View.ExcellentBreakWeight) {
        throw new RuntimeException("breakWeight != ExcellentBreakWeight");
    }
}
 
源代码10 项目: netbeans   文件: FoldMultiLineView.java
protected @Override void reloadChildren(int index, int removeLength, int startOffset, int endOffset) {
    // TODO uncomment assert (index == 0 && removeLength == 0
        // && startOffset == getStartOffset() && endOffset == getEndOffset());

    // Rebuild all the present child views completely
    index = 0;
    removeLength = getViewCount();

    Element lineElem = getElement(); // starting line element
    View[] added = null;
    ViewFactory f = getViewFactory();
    if (f != null) {
        int lineElemEndOffset = lineElem.getEndOffset();
        // Ending offset of the previously created view - here start with
        //   begining of the first line
        int lastViewEndOffset = lineElem.getStartOffset();

        List childViews = new ArrayList();
        // Append ending fragment if necessary
        // asserted non-empty list => foldEndOffset populated
        if (lastViewEndOffset < lineElemEndOffset) { // need ending fragment
            View lineView = f.create(lineElem);
            View endingFrag = lineView.createFragment(lastViewEndOffset, lineElemEndOffset);
            childViews.add(endingFrag);
            // lastViewEndOffset = lineElemEndOffset;  <- can be ignored here
        }

        added = new View[childViews.size()];
        childViews.toArray(added);
    }

    
    replace(index, removeLength, added);
}
 
源代码11 项目: netbeans   文件: BaseDocument.java
public void checkTrailingSpaces(int offset) {
    try {
        int lineNum = Utilities.getLineOffset(this, offset);
        int lastEditedLine = lastPositionEditedByTyping != null ? Utilities.getLineOffset(this, lastPositionEditedByTyping.getOffset()) : -1;
        if (lastEditedLine != -1 && lastEditedLine != lineNum) {
            // clear trailing spaces in the last edited line
            Element root = getDefaultRootElement();
            Element elem = root.getElement(lastEditedLine);
            int start = elem.getStartOffset();
            int end = elem.getEndOffset();
            String line = getText(start, end - start);

            int endIndex = line.length() - 1;
            if (endIndex >= 0 && line.charAt(endIndex) == '\n') {
                endIndex--;
                if (endIndex >= 0 && line.charAt(endIndex) == '\r') {
                    endIndex--;
                }
            }

            int startIndex = endIndex;
            while (startIndex >= 0 && Character.isWhitespace(line.charAt(startIndex)) && line.charAt(startIndex) != '\n' &&
                    line.charAt(startIndex) != '\r') {
                startIndex--;
            }
            startIndex++;
            if (startIndex >= 0 && startIndex <= endIndex) {
                remove(start + startIndex, endIndex - startIndex + 1);
            }
        }
    } catch (BadLocationException e) {
        LOG.log(Level.WARNING, null, e);
    }
}
 
源代码12 项目: TencentKona-8   文件: bug6857057.java
bug6857057() {
    Element elem = new StubBranchElement(" G L Y P H V");
    GlyphView view = new GlyphView(elem);
    float pos = elem.getStartOffset();
    float len = elem.getEndOffset() - pos;
    int res = view.getBreakWeight(View.X_AXIS, pos, len);
    if (res != View.ExcellentBreakWeight) {
        throw new RuntimeException("breakWeight != ExcellentBreakWeight");
    }
}
 
源代码13 项目: hortonmachine   文件: MapcalcDocument.java
private String getLine( String content, int offset ) {
    int line = rootElement.getElementIndex(offset);
    Element lineElement = rootElement.getElement(line);
    int start = lineElement.getStartOffset();
    int end = lineElement.getEndOffset();
    return content.substring(start, end - 1);
}
 
源代码14 项目: java-swing-tips   文件: MainPanel.java
@Override public void setText(String str) {
  super.setText(str);
  FontMetrics fm = getFontMetrics(getFont());
  Document doc = getDocument();
  Element root = doc.getDefaultRootElement();
  int lineCount = root.getElementCount(); // = root.getElementIndex(doc.getLength());
  int maxWidth = 10;
  try {
    for (int i = 0; i < lineCount; i++) {
      Element e = root.getElement(i);
      int rangeStart = e.getStartOffset();
      int rangeEnd = e.getEndOffset();
      String line = doc.getText(rangeStart, rangeEnd - rangeStart);
      int width = fm.stringWidth(line);
      if (maxWidth < width) {
        maxWidth = width;
      }
    }
  } catch (BadLocationException ex) {
    // should never happen
    RuntimeException wrap = new StringIndexOutOfBoundsException(ex.offsetRequested());
    wrap.initCause(ex);
    throw wrap;
  }
  setRows(lineCount);
  setColumns(1 + maxWidth / getColumnWidth());
}
 
private void removeFromEnd(Document document, Element root) {
    //  We use start minus 1 to make sure we remove the newline
    //  character of the previous line

    Element line = root.getElement(root.getElementCount() - 1);
    int start = line.getStartOffset();
    int end = line.getEndOffset();

    try {
        document.remove(start - 1, end - start);
    } catch (BadLocationException ex) {
        LOG.log(Level.WARNING, ex.getMessage(), ex);
    }
}
 
源代码16 项目: java-swing-tips   文件: MainPanel.java
public static int getWordStart(JTextComponent c, int offs) throws BadLocationException {
  Element line = Optional.ofNullable(Utilities.getParagraphElement(c, offs))
      .orElseThrow(() -> new BadLocationException("No word at " + offs, offs));
  Document doc = c.getDocument();
  int lineStart = line.getStartOffset();
  int lineEnd = Math.min(line.getEndOffset(), doc.getLength());
  int offs2 = offs;
  Segment seg = SegmentCache.getSharedSegment();
  doc.getText(lineStart, lineEnd - lineStart, seg);
  if (seg.count > 0) {
    BreakIterator words = BreakIterator.getWordInstance(c.getLocale());
    words.setText(seg);
    int wordPosition = seg.offset + offs - lineStart;
    if (wordPosition >= words.last()) {
      wordPosition = words.last() - 1;
      words.following(wordPosition);
      offs2 = lineStart + words.previous() - seg.offset;
    } else {
      words.following(wordPosition);
      offs2 = lineStart + words.previous() - seg.offset;
      for (int i = offs; i > offs2; i--) {
        char ch = seg.charAt(i - seg.offset);
        if (ch == '_' || ch == '-') {
          offs2 = i + 1;
          break;
        }
      }
    }
  }
  SegmentCache.releaseSharedSegment(seg);
  return offs2;
}
 
源代码17 项目: openjdk-8   文件: CAccessibleText.java
static int[] getRangeForLine(final Accessible a, final int lineIndex) {
    Accessible sa = CAccessible.getSwingAccessible(a);
    if (!(sa instanceof JTextComponent)) return null;

    final JTextComponent jc = (JTextComponent) sa;
    final Element root = jc.getDocument().getDefaultRootElement();
    final Element line = root.getElement(lineIndex);
    if (line == null) return null;

    return new int[] { line.getStartOffset(), line.getEndOffset() };
}
 
源代码18 项目: nb-springboot   文件: ValueCompletionItem.java
@Override
public void defaultAction(JTextComponent jtc) {
    logger.log(Level.FINER, "Accepted value completion: {0}", hint.toString());
    try {
        StyledDocument doc = (StyledDocument) jtc.getDocument();
        // calculate the amount of chars to remove (by default from dot up to caret position)
        int lenToRemove = caretOffset - dotOffset;
        if (overwrite) {
            // NOTE: the editor removes by itself the word at caret when ctrl + enter is pressed
            // the document state here is different from when the completion was invoked thus we have to
            // find again the offset of the equal sign in the line
            Element lineElement = doc.getParagraphElement(caretOffset);
            String line = doc.getText(lineElement.getStartOffset(), lineElement.getEndOffset() - lineElement.getStartOffset());
            int equalSignIndex = line.indexOf('=');
            int colonIndex = line.indexOf(':');
            int commaIndex = line.indexOf(',', dotOffset - lineElement.getStartOffset());
            if (equalSignIndex >= 0 && dotOffset < equalSignIndex) {
                // from dot to equal sign
                lenToRemove = lineElement.getStartOffset() + equalSignIndex - dotOffset;
            } else if (colonIndex >= 0 && dotOffset < colonIndex) {
                // from dot to colon
                lenToRemove = lineElement.getStartOffset() + colonIndex - dotOffset;
            } else if (commaIndex >= 0) {
                // from dot to comma
                lenToRemove = lineElement.getStartOffset() + commaIndex - dotOffset;
            } else {
                // from dot to end of line (except line terminator)
                lenToRemove = lineElement.getEndOffset() - 1 - dotOffset;
            }
        }
        // remove characters from dot then insert new text
        doc.remove(dotOffset, lenToRemove);
        doc.insertString(dotOffset, hint.getValue().toString(), null);
        // close the code completion box
        if (!continueCompletion) {
            Completion.get().hideAll();
        }
    } catch (BadLocationException ex) {
        Exceptions.printStackTrace(ex);
    }
}
 
源代码19 项目: netbeans   文件: GapBranchElement.java
/**
 * Implementation that remembers the last returned element index
 * and checks the element at the last index when next called.
 * <br>
 * This may improve performance if there are typically many repetitive calls
 * with offset values hitting the last returned element index.
 */
public int getElementIndex(int offset) {
    int low = 0;
    int high = getElementCount() - 1;

    if (high == -1) { // no children => return -1
        return -1;
    }

    int lastIndex = lastReturnedElementIndex; // make copy to be thread-safe
    if (lastIndex >= low && lastIndex <= high) {
        Element lastElem = getElement(lastIndex);
        int lastElemStartOffset = lastElem.getStartOffset();
        if (offset >= lastElemStartOffset) {
            int lastElemEndOffset = lastElem.getEndOffset();
            if (offset < lastElemEndOffset) { // hit
                return lastIndex;
            } else { // above
                low = lastIndex + 1;
            }
        } else { // below lastIndex
            high = lastIndex - 1;
        }
    }

    while (low <= high) {
        int mid = (low + high) / 2;
        int elemStartOffset = ((Element)children.get(mid)).getStartOffset();

        if (elemStartOffset < offset) {
            low = mid + 1;
        } else if (elemStartOffset > offset) {
            high = mid - 1;
        } else { // element starts at offset
            lastReturnedElementIndex = mid;
            return mid;
        }
    }

    if (high < 0) {
        high = 0;
    }
    lastReturnedElementIndex = high;
    return high;
}
 
源代码20 项目: netbeans   文件: ToolTipAnnotation.java
private static String getIdentifier (
    JPDADebugger debugger,
    StyledDocument doc,
    JEditorPane ep,
    int offset,
    boolean[] isFunctionPtr
) {
    // do always evaluation if the tooltip is invoked on a text selection
    String t = null;
    if ( (ep.getSelectionStart () <= offset) &&
         (offset <= ep.getSelectionEnd ())
    ) {
        t = ep.getSelectedText ();
    }
    if (t != null) {
        return t;
    }
    int line = NbDocument.findLineNumber (
        doc,
        offset
    );
    int col = NbDocument.findLineColumn (
        doc,
        offset
    );
    try {
        Element lineElem =
            NbDocument.findLineRootElement (doc).
            getElement (line);

        if (lineElem == null) {
            return null;
        }
        int lineStartOffset = lineElem.getStartOffset ();
        int lineLen = lineElem.getEndOffset() - lineStartOffset;
        t = doc.getText (lineStartOffset, lineLen);
        int identStart = col;
        while (identStart > 0 &&
            (Character.isJavaIdentifierPart (
                t.charAt (identStart - 1)
            ) ||
            (t.charAt (identStart - 1) == '.'))) {
            identStart--;
        }
        int identEnd = col;
        while (identEnd < lineLen &&
               Character.isJavaIdentifierPart(t.charAt(identEnd))
        ) {
            identEnd++;
        }

        if (identStart == identEnd) {
            return null;
        }

        String ident = t.substring (identStart, identEnd);
        //if (JS_KEYWORDS.contains(ident)) {
            // JS keyword => Do not show anything
        //    return null;
        //}

        while (identEnd < lineLen &&
               Character.isWhitespace(t.charAt(identEnd))
        ) {
            identEnd++;
        }
        if (identEnd < lineLen && t.charAt(identEnd) == '(') {
            // We're at a function call
            isFunctionPtr[0] = true;
        }
        return ident;
    } catch (BadLocationException e) {
        return null;
    }
}