Java Code Examples for javax.swing.text.Element#getElementIndex()

The following examples show how to use javax.swing.text.Element#getElementIndex() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SyntaxView.java    From jpexs-decompiler with GNU General Public License v3.0 6 votes vote down vote up
@Override
public Shape modelToView(int pos, Shape a, Position.Bias b) throws BadLocationException {
    // line coordinates
    Document doc = getDocument();
    Element map = getElement();
    int lineIndex = map.getElementIndex(pos);
    if (lineIndex < 0) {
        return lineToRect(a, 0);
    }
    Rectangle lineArea = lineToRect(a, lineIndex);

    // determine span from the start of the line
    int tabBase = lineArea.x;
    Element line = map.getElement(lineIndex);
    int p0 = line.getStartOffset();
    Segment s = new Segment();
    doc.getText(p0, pos - p0, s);
    int xOffs = UniTools.getTabbedTextWidth(s, metrics, tabBase, this,p0);

    // fill in the results and return
    lineArea.x += xOffs;
    lineArea.width = 1;
    lineArea.height = metrics.getHeight();
    return lineArea;
}
 
Example 2
Source File: OutputEditorKit.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/** The operation to perform when this action is triggered. */
public void actionPerformed(ActionEvent e) {
    JTextComponent target = getTextComponent(e);
    if (target != null) {
        Document doc = target.getDocument();
        Element map = doc.getDefaultRootElement();
        int offs = target.getCaretPosition();
        int lineIndex = map.getElementIndex(offs);
        int lineEnd = map.getElement(lineIndex).getEndOffset() - 1;

        if (select) {
            target.moveCaretPosition(lineEnd);
        } else {
            target.setCaretPosition(lineEnd);
        }
    }            
}
 
Example 3
Source File: LineDocumentUtils.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/** Count of rows between these two positions */
public static int getLineCount(@NonNull LineDocument doc, int startOffset, int endOffset) {
    if (startOffset > endOffset) {
        return 0;
    }
    Element lineRoot = doc.getParagraphElement(0).getParentElement();
    return lineRoot.getElementIndex(endOffset) - lineRoot.getElementIndex(startOffset) + 1;
}
 
Example 4
Source File: JNumberedTextArea.java    From constellation with Apache License 2.0 5 votes vote down vote up
private String getLineNumbersText() {
    final int caretPosition = textArea.getDocument().getLength();
    final Element root = textArea.getDocument().getDefaultRootElement();
    final StringBuilder builder = new StringBuilder();
    builder.append("1").append(System.lineSeparator());

    for (int elementIndex = 2; elementIndex < root.getElementIndex(caretPosition) + 2; elementIndex++) {
        builder.append(elementIndex).append(System.lineSeparator());
    }

    return builder.toString();
}
 
Example 5
Source File: MainPanel.java    From java-swing-tips with MIT License 5 votes vote down vote up
private void processChangedLines(int offset, int length) throws BadLocationException {
  Element root = getDefaultRootElement();
  String content = getText(0, getLength());
  int startLine = root.getElementIndex(offset);
  int endLine = root.getElementIndex(offset + length);
  for (int i = startLine; i <= endLine; i++) {
    applyHighlighting(content, i);
  }
}
 
Example 6
Source File: CAccessibleText.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
static int getLineNumberForIndex(final Accessible a, int index) {
    final Accessible sa = CAccessible.getSwingAccessible(a);
    if (!(sa instanceof JTextComponent)) return -1;

    final JTextComponent jc = (JTextComponent) sa;
    final Element root = jc.getDocument().getDefaultRootElement();

    // treat -1 special, returns the current caret position
    if (index == -1) index = jc.getCaretPosition();

    // Determine line number (can be -1)
    return root.getElementIndex(index);
}
 
Example 7
Source File: CollapsedView.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private View getExpandedView(){
    Element parentElem = getElement().getParentElement();
    int sei = parentElem.getElementIndex(getStartOffset());
    int so = parentElem.getElement(sei).getStartOffset();
    
    int eei = parentElem.getElementIndex(getEndOffset());
    int eo = parentElem.getElement(eei).getEndOffset();
    
    LockView fakeView = new LockView(
    new DrawEngineFakeDocView(parentElem, so, eo, false, true)
    );
    RootView rootView = new RootView();
    rootView.setView(fakeView);
    return fakeView;
}
 
Example 8
Source File: CAccessibleText.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
static int getLineNumberForIndex(final Accessible a, int index) {
    final Accessible sa = CAccessible.getSwingAccessible(a);
    if (!(sa instanceof JTextComponent)) return -1;

    final JTextComponent jc = (JTextComponent) sa;
    final Element root = jc.getDocument().getDefaultRootElement();

    // treat -1 special, returns the current caret position
    if (index == -1) index = jc.getCaretPosition();

    // Determine line number (can be -1)
    return root.getElementIndex(index);
}
 
Example 9
Source File: CAccessibleText.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
static int getLineNumberForIndex(final Accessible a, int index) {
    final Accessible sa = CAccessible.getSwingAccessible(a);
    if (!(sa instanceof JTextComponent)) return -1;

    final JTextComponent jc = (JTextComponent) sa;
    final Element root = jc.getDocument().getDefaultRootElement();

    // treat -1 special, returns the current caret position
    if (index == -1) index = jc.getCaretPosition();

    // Determine line number (can be -1)
    return root.getElementIndex(index);
}
 
Example 10
Source File: LineNumbers.java    From jadx with Apache License 2.0 5 votes vote down vote up
@Override
public void caretUpdate(CaretEvent e) {
	int caretPosition = codeArea.getCaretPosition();
	Element root = codeArea.getDocument().getDefaultRootElement();
	int currentLine = root.getElementIndex(caretPosition);
	if (lastLine != currentLine) {
		repaint();
		lastLine = currentLine;
	}
}
 
Example 11
Source File: CAccessibleText.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
static int getLineNumberForIndex(final Accessible a, int index) {
    final Accessible sa = CAccessible.getSwingAccessible(a);
    if (!(sa instanceof JTextComponent)) return -1;

    final JTextComponent jc = (JTextComponent) sa;
    final Element root = jc.getDocument().getDefaultRootElement();

    // treat -1 special, returns the current caret position
    if (index == -1) index = jc.getCaretPosition();

    // Determine line number (can be -1)
    return root.getElementIndex(index);
}
 
Example 12
Source File: CAccessibleText.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
static int getLineNumberForIndex(final Accessible a, int index) {
    final Accessible sa = CAccessible.getSwingAccessible(a);
    if (!(sa instanceof JTextComponent)) return -1;

    final JTextComponent jc = (JTextComponent) sa;
    final Element root = jc.getDocument().getDefaultRootElement();

    // treat -1 special, returns the current caret position
    if (index == -1) index = jc.getCaretPosition();

    // Determine line number (can be -1)
    return root.getElementIndex(index);
}
 
Example 13
Source File: JavaMoveCodeElementAction.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private int getLineEnd(BaseDocument doc, int offset) {
    Element rootElement = doc.getDefaultRootElement();
    int lineNumber = rootElement.getElementIndex(offset);
    return lineNumber < 0 ? lineNumber : rootElement.getElement(lineNumber).getEndOffset();
}
 
Example 14
Source File: OQLEditorComponent.java    From visualvm with GNU General Public License v2.0 4 votes vote down vote up
private static int followedPosition(JTextComponent tc) {
    Element root = tc.getDocument().getDefaultRootElement();
    return root.getElementIndex(tc.getCaretPosition()) * 6;
}
 
Example 15
Source File: JavaMoveCodeElementAction.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private int getLineStart(BaseDocument doc, int offset) {
    Element rootElement = doc.getDefaultRootElement();
    int lineNumber = rootElement.getElementIndex(offset);
    return lineNumber < 0 ? lineNumber : rootElement.getElement(lineNumber).getStartOffset();
}
 
Example 16
Source File: MainPanel.java    From java-swing-tips with MIT License 4 votes vote down vote up
private int getLineAtPoint(int y) {
  Element root = textArea.getDocument().getDefaultRootElement();
  int pos = textArea.viewToModel(new Point(0, y));
  // Java 9: int pos = textArea.viewToModel2D(new Point(0, y));
  return root.getElementIndex(pos);
}
 
Example 17
Source File: GapBoxView.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/**
     * Loads child views in a custom way.
     *
     * @param index index at which the views should be added/replaced.
     * @param removeLength number of removed children views. It is useful
     *  when rebuilding children for a portion of the view.
     * @param startOffset starting offset from which the loading starts.
     * @param endOffset ending offset where the loading ends.
     */
    protected void customReloadChildren(int index, int removeLength,
    int startOffset, int endOffset) {

        View[] added = null;
        ViewFactory f = getViewFactory();
        // Null view factory can mean that one of the grand parents is already disconnected
        // from the view hierarchy. No added children for null factory.
        
        if (f != null) {
            Element elem = getElement();

            int elementCount = elem.getElementCount();
            int elementIndex = (elem != null) ? elem.getElementIndex(startOffset) : -1;
            if (elementIndex >= elementCount) {
                return; // Create no after last element
            }
            List childViews = new ArrayList();
            int viewCount = getViewCount();

            loop:
            while (startOffset < endOffset) {
                // Create custom child
                View childView = createCustomView(f, startOffset, endOffset, elementIndex);
                if (childView == null) {
                    throw new IllegalStateException("No view created for area (" // NOI18N
                        + startOffset + ", " + endOffset + ")"); // NOI18N
                }

                // Assuming childView.getStartOffset() is at startOffset
                childViews.add(childView);

                // Update elementIndex
                int childViewEndOffset = childView.getEndOffset();
                while (childViewEndOffset > endOffset) {
/*                    throw new IllegalStateException(
                        "childViewEndOffset=" + childViewEndOffset // NOI18N
                        + " > endOffset=" + endOffset // NOI18N
                    );
 */
                    /* The created child view interferes with a view
                     * that is still present and which is not planned
                     * to be removed.
                     * This can happen e.g. when a fold hierarchy change
                     * (caused by a document change) is fired
                     * prior to the document change gets fired
                     * to the view hierarchy.
                     * The fix for that situation is to continue to remove
                     * the present views until the end of the created view will match
                     * a beginning of a present view.
                     */
                    if (index + removeLength >= viewCount) {
                        // Should not happen but can't remove past the last view
                        break;
                    }
                    endOffset = getView(index + removeLength).getEndOffset();
                    removeLength++;
                    if (LOG.isLoggable(Level.FINE)) {
                        LOG.fine(
                            "GapBoxView.customReloadChildren(): Increased removeLength to "  // NOI18N
                            + removeLength + ", eo=" + endOffset // NOI18N
                        );
                    }
                }

                Element childElem = elem.getElement(elementIndex);
                while (childElem.getEndOffset() <= childViewEndOffset) {
                    elementIndex++;
                    if (elementIndex == elementCount) {
                        // #115034
                        break loop;
                    }
                    childElem = elem.getElement(elementIndex);
                }

                startOffset = childViewEndOffset;
            }

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

        replace(index, removeLength, added);
    }
 
Example 18
Source File: BaseCaret.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/**
 * Extend rectangular selection either by char in a specified selection
 * or by word (if ctrl is pressed).
 *
 * @param toRight true for right or false for left.
 * @param ctrl 
 */
public void extendRectangularSelection(boolean toRight, boolean ctrl) {
    JTextComponent c = component;
    Document doc = c.getDocument();
    int dotOffset = getDot();
    Element lineRoot = doc.getDefaultRootElement();
    int lineIndex = lineRoot.getElementIndex(dotOffset);
    Element lineElement = lineRoot.getElement(lineIndex);
    float charWidth;
    LockedViewHierarchy lvh = ViewHierarchy.get(c).lock();
    try {
        charWidth = lvh.getDefaultCharWidth();
    } finally {
        lvh.unlock();
    }
    int newDotOffset = -1;
    try {
        int newlineOffset = lineElement.getEndOffset() - 1;
        Rectangle newlineRect = c.modelToView(newlineOffset);
        if (!ctrl) {
            if (toRight) {
                if (rsDotRect.x < newlineRect.x) {
                    newDotOffset = dotOffset + 1;
                } else {
                    rsDotRect.x += charWidth;
                }
            } else { // toLeft
                if (rsDotRect.x > newlineRect.x) {
                    rsDotRect.x -= charWidth;
                    if (rsDotRect.x < newlineRect.x) { // Fix on rsDotRect
                        newDotOffset = newlineOffset;
                    }
                } else {
                    newDotOffset = Math.max(dotOffset - 1, lineElement.getStartOffset());
                }
            }

        } else { // With Ctrl
            int numVirtualChars = 8; // Number of virtual characters per one Ctrl+Shift+Arrow press
            if (toRight) {
                if (rsDotRect.x < newlineRect.x) {
                    newDotOffset = Math.min(Utilities.getNextWord(c, dotOffset), lineElement.getEndOffset() - 1);
                } else { // Extend virtually
                    rsDotRect.x += numVirtualChars * charWidth;
                }
            } else { // toLeft
                if (rsDotRect.x > newlineRect.x) { // Virtually extended
                    rsDotRect.x -= numVirtualChars * charWidth;
                    if (rsDotRect.x < newlineRect.x) {
                        newDotOffset = newlineOffset;
                    }
                } else {
                    newDotOffset = Math.max(Utilities.getPreviousWord(c, dotOffset), lineElement.getStartOffset());
                }
            }
        }

        if (newDotOffset != -1) {
            rsDotRect = c.modelToView(newDotOffset);
            moveDot(newDotOffset); // updates rs and fires state change
        } else {
            updateRectangularSelectionPaintRect();
            fireStateChanged();
        }
    } catch (BadLocationException ex) {
        // Leave selection as is
    }
}
 
Example 19
Source File: DocUtils.java    From netbeans with Apache License 2.0 2 votes vote down vote up
/** 
 * Return line index (line number - 1) for some offset in document.
 * 
 * @param doc document to operate on.
 * @param offset offset in document.
 * @return line index &gt;=0 since document always contains at least single '\n'.
 *  Returns 0 if offset &lt;=0. Returns last line index if offset is beyond document's end.
 */
public static int getLineIndex(Document doc, int offset) {
    Element lineRoot = doc.getDefaultRootElement();
    return lineRoot.getElementIndex(offset);
}
 
Example 20
Source File: LineDocumentUtils.java    From netbeans with Apache License 2.0 2 votes vote down vote up
/**
 * Return line index (line number - 1) for the given offset in the document.
 *
 * @param doc document to operate on
 * @param offset position in document where to start searching
 */
public static int getLineIndex(@NonNull LineDocument doc, int offset) throws BadLocationException {
    checkOffsetValid(doc, offset);
    Element lineRoot = doc.getParagraphElement(0).getParentElement();
    return lineRoot.getElementIndex(offset);
}