Java Code Examples for javax.swing.text.Document#getDefaultRootElement()

The following examples show how to use javax.swing.text.Document#getDefaultRootElement() . These examples are extracted from open source projects. 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
private String getCurrentText() {
    Document doc = this.getDocument();
    int dot = this.getCaretPosition();
    Element root = doc.getDefaultRootElement();
    int index = root.getElementIndex(dot);
    Element elem = root.getElement(index);
    int start = elem.getStartOffset();
    int len = dot - start;
    try {
        doc.getText(start, len, seg);
    } catch (BadLocationException ble) {
        ble.printStackTrace();
        return "";
    }
    return seg.toString();
}
 
Example 2
Source Project: java-swing-tips   File: MainPanel.java    License: MIT License 6 votes vote down vote up
private MainPanel() {
  super(new BorderLayout());
  int maskRange = 2;
  HighlightPainter highlightPainter = new DefaultHighlightPainter(Color.GRAY);
  JTextArea textArea = new JTextArea();
  textArea.setText("aaaaaaaasdfasdfasdfasdf\nasdfasdfasdfasdfasdfasdf\n1234567890\naaaaaaaaaaaaaaaaaasdfasd");
  ((AbstractDocument) textArea.getDocument()).setDocumentFilter(new NonEditableLineDocumentFilter(maskRange));
  try {
    Highlighter hilite = textArea.getHighlighter();
    Document doc = textArea.getDocument();
    Element root = doc.getDefaultRootElement();
    for (int i = 0; i < maskRange; i++) { // root.getElementCount(); i++) {
      Element elem = root.getElement(i);
      hilite.addHighlight(elem.getStartOffset(), elem.getEndOffset() - 1, highlightPainter);
    }
  } catch (BadLocationException ex) {
    // should never happen
    RuntimeException wrap = new StringIndexOutOfBoundsException(ex.offsetRequested());
    wrap.initCause(ex);
    throw wrap;
  }
  add(new JScrollPane(textArea));
  setPreferredSize(new Dimension(320, 240));
}
 
Example 3
Source Project: netbeans   File: OutputEditorKit.java    License: 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 4
Source Project: java-swing-tips   File: MainPanel.java    License: MIT License 6 votes vote down vote up
@Override public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
  Document doc = fb.getDocument();
  Element root = doc.getDefaultRootElement();
  int count = root.getElementCount();
  int index = root.getElementIndex(offset);
  Element cur = root.getElement(index);
  int promptPosition = cur.getStartOffset() + PROMPT.length();
  if (index == count - 1 && offset - promptPosition >= 0) {
    String str = text;
    if (LB.equals(str)) {
      String line = doc.getText(promptPosition, offset - promptPosition);
      // String[] args = line.split("\\s");
      String[] args = Stream.of(line.split(","))
        .map(String::trim)
        .filter(s -> !s.isEmpty())
        .toArray(String[]::new);
      String cmd = args[0];
      if (cmd.isEmpty()) {
        str = String.format("%n%s", PROMPT);
      } else {
        str = String.format("%n%s: command not found%n%s", cmd, PROMPT);
      }
    }
    fb.replace(offset, length, str, attrs);
  }
}
 
Example 5
Source Project: netbeans   File: NbEditorUtilities.java    License: Apache License 2.0 6 votes vote down vote up
/** Get the line object from the given position.
 * @param doc document for which the line is being retrieved
 * @param offset position in the document
 * @param original whether to retrieve the original line (true) before
 *   the modifications were done or the current line (false)
 * @return the line object
 */
public static Line getLine(Document doc, int offset, boolean original) {
    DataObject dob = getDataObject(doc);
    if (dob != null) {
        LineCookie lc = (LineCookie)dob.getCookie(LineCookie.class);
        if (lc != null) {
            Line.Set lineSet = lc.getLineSet();
            if (lineSet != null) {
                Element lineRoot = (doc instanceof AbstractDocument)
                    ? ((AbstractDocument)doc).getParagraphElement(0).getParentElement()
                    : doc.getDefaultRootElement();
                int lineIndex = lineRoot.getElementIndex(offset);
                return original
                       ? lineSet.getOriginal(lineIndex)
                       : lineSet.getCurrent(lineIndex);
            }
        }
    }
    return null;
}
 
Example 6
Source Project: netbeans   File: FoldView.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public JComponent getToolTip(double x, double y, Shape allocation) {
    Container container = getContainer();
    if (container instanceof JEditorPane) {
        JEditorPane editorPane = (JEditorPane) getContainer();
        JEditorPane tooltipPane = new JEditorPane();
        EditorKit kit = editorPane.getEditorKit();
        Document doc = getDocument();
        if (kit != null && doc != null) {
            Element lineRootElement = doc.getDefaultRootElement();
            tooltipPane.putClientProperty(FoldViewFactory.DISPLAY_ALL_FOLDS_EXPANDED_PROPERTY, true);
            try {
                // Start-offset of the fold => line start => position
                int lineIndex = lineRootElement.getElementIndex(fold.getStartOffset());
                Position pos = doc.createPosition(
                        lineRootElement.getElement(lineIndex).getStartOffset());
                // DocumentView.START_POSITION_PROPERTY
                tooltipPane.putClientProperty("document-view-start-position", pos); // NOI18N
                // End-offset of the fold => line end => position
                lineIndex = lineRootElement.getElementIndex(fold.getEndOffset());
                pos = doc.createPosition(lineRootElement.getElement(lineIndex).getEndOffset());
                // DocumentView.END_POSITION_PROPERTY
                tooltipPane.putClientProperty("document-view-end-position", pos); // NOI18N
                tooltipPane.putClientProperty("document-view-accurate-span", true); // NOI18N
                // Set the same kit and document
                tooltipPane.setEditorKit(kit);
                tooltipPane.setDocument(doc);
                tooltipPane.setEditable(false);
                return new FoldToolTip(editorPane, tooltipPane, getBorderColor());
            } catch (BadLocationException e) {
                // => return null
            }
        }
    }
    return null;
}
 
Example 7
Source Project: netbeans   File: LockView.java    License: Apache License 2.0 5 votes vote down vote up
public Element getElement() {
    if (view != null) {
        return view.getElement();
    }
    Document doc = getDocument();
    return (doc != null) ? doc.getDefaultRootElement() : null;
}
 
Example 8
private void removeLines(DocumentEvent e) {
	// The root Element of the Document will tell us the total number
	// of line in the Document.

	Document document = e.getDocument();
	Element root = document.getDefaultRootElement();

	while (root.getElementCount() > maximumLines) {
		if (isRemoveFromStart) {
			removeFromStart(document, root);
		} else {
			removeFromEnd(document, root);
		}
	}
}
 
Example 9
/**
 * Perform the goto operation.
 *
 * @return whether the dialog should be made invisible or not
 */
private boolean performGoto() {
    JTextComponent c = getTargetComponent();
    String text = (String) gotoCombo.getEditor().getItem();
    if (c != null) {
        try {
            int lineNumber = Integer.parseInt(text);
            if (lineNumber == 0) { // Works in vim to jump to begining
                lineNumber = 1;
            }
            int lineIndex = lineNumber - 1;
            Document doc = c.getDocument();
            Element rootElem = doc.getDefaultRootElement();
            int lineCount = rootElem.getElementCount();
            if (lineIndex >= 0) {
                if (lineIndex >= lineCount) {
                    lineIndex = lineCount - 1;
                }
                int offset = rootElem.getElement(lineIndex).getStartOffset();
                c.setCaretPosition(offset);
                return true;
            } // else: lineIndex < 0 => beep and return false
        } catch (NumberFormatException e) {
            // Contains letters or other chars -> attempt bookmarks
            BookmarkManager lockedBookmarkManager = BookmarkManager.getLocked();
            try {
                BookmarkInfo bookmark = lockedBookmarkManager.findBookmarkByNameOrKey(text, false);
                if (bookmark != null) {
                    BookmarkUtils.postOpenEditor(bookmark);
                    return true;
                } // else: unknown bookmark => beep
            } finally {
                lockedBookmarkManager.unlock();
            }
        }
    }
    c.getToolkit().beep();
    return false;
}
 
Example 10
Source Project: netbeans   File: BookmarkUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static int lineIndex2Offset(Document doc, int lineIndex) {
    javax.swing.text.Element lineRoot = doc.getDefaultRootElement();
    int offset = (lineIndex < lineRoot.getElementCount())
            ? lineRoot.getElement(lineIndex).getStartOffset()
            : doc.getLength();
    return offset;
    
}
 
Example 11
@Override
int getLineOfCaret() {
	Document doc = textComponent.getDocument();
	Element root = doc.getDefaultRootElement();
	return root.getElementIndex(textComponent.getCaretPosition());
}
 
Example 12
Source Project: netbeans   File: GetJavaWord.java    License: Apache License 2.0 4 votes vote down vote up
static String forPane(JEditorPane p) {
    if (p == null) return null;
 
    String selection = p.getSelectedText ();
 
    if ( selection != null && selection.length() > 0 ) {
        return selection;
    } else {
 
        // try to guess which word is underneath the caret's dot.
 
        Document doc = p.getDocument();
        Element lineRoot;
 
        if (doc instanceof StyledDocument) {
            lineRoot = NbDocument.findLineRootElement((StyledDocument)doc);
        } else {
            lineRoot = doc.getDefaultRootElement();
        }
        int dot = p.getCaret().getDot();
        Element line = lineRoot.getElement(lineRoot.getElementIndex(dot));
 
        if (line == null) return null;
 
        String text = null;
        try {
            text = doc.getText(line.getStartOffset(),
                line.getEndOffset() - line.getStartOffset());
        } catch (BadLocationException e) {
            return null;
        }
        
        if ( text == null )
            return null;
        int pos = dot - line.getStartOffset();

        if ( pos < 0 || pos >= text.length() )
            return null;

        int bix, eix;

        for( bix = Character.isJavaIdentifierPart( text.charAt( pos ) ) ? pos : pos - 1;
                bix >= 0 && Character.isJavaIdentifierPart( text.charAt( bix ) ); bix-- );
        for( eix = pos; eix < text.length() && Character.isJavaIdentifierPart( text.charAt( eix )); eix++ );

        return bix == eix ? null : text.substring( bix + 1, eix  );
    }
}
 
Example 13
Source Project: netbeans   File: FixLineSyntaxState.java    License: Apache License 2.0 4 votes vote down vote up
private static Element getLineRoot(Document doc) {
    return doc.getDefaultRootElement();
}
 
Example 14
Source Project: netbeans   File: BaseCaret.java    License: 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 15
private int getLineIndex(Document doc, int offset) {
    Element root = doc.getDefaultRootElement();
    return root.getElementIndex(offset);
}
 
Example 16
Source Project: netbeans   File: EditorCaret.java    License: 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 true for ctrl pressed.
 */
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
            LineDocument lineDoc = LineDocumentUtils.asRequired(doc, LineDocument.class);
            int numVirtualChars = 8; // Number of virtual characters per one Ctrl+Shift+Arrow press
            if (toRight) {
                if (rsDotRect.x < newlineRect.x) {
                    newDotOffset = Math.min(LineDocumentUtils.getNextWordStart(lineDoc, 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(LineDocumentUtils.getPreviousWordStart(lineDoc, dotOffset), lineElement.getStartOffset());
                }
            }
        }

        if (newDotOffset != -1) {
            rsDotRect = c.modelToView(newDotOffset);
            moveDot(newDotOffset); // updates rs and fires state change
        } else {
            updateRectangularSelectionPaintRect();
            fireStateChanged(null);
        }
    } catch (BadLocationException ex) {
        // Leave selection as is
    }
}
 
Example 17
public static int getStartOfLine(Document document, int line) {
    Element root = document.getDefaultRootElement();
    line = Math.max(line, 1);
    line = Math.min(line, root.getElementCount());
    return root.getElement(line - 1).getStartOffset();
}
 
Example 18
Source Project: netbeans   File: BookmarkUtils.java    License: Apache License 2.0 4 votes vote down vote up
public static int offset2LineIndex(Document doc, int offset) {
    javax.swing.text.Element lineRoot = doc.getDefaultRootElement();
    int lineIndex = lineRoot.getElementIndex(offset);
    return lineIndex;
    
}
 
Example 19
@Override
public int viewToModel(float fx, float fy, Shape a, Position.Bias[] bias) {
    // PENDING(prinz) properly calculate bias
    bias[0] = Position.Bias.Forward;

    Rectangle alloc = a.getBounds();
    Document doc = getDocument();
    int x = (int) fx;
    int y = (int) fy;
    if (y < alloc.y) {
        // above the area covered by this icon, so the the position
        // is assumed to be the start of the coverage for this view.
        return getStartOffset();
    } else if (y > alloc.y + alloc.height) {
        // below the area covered by this icon, so the the position
        // is assumed to be the end of the coverage for this view.
        return getEndOffset() - 1;
    } else {
        // positioned within the coverage of this view vertically,
        // so we figure out which line the point corresponds to.
        // if the line is greater than the number of lines contained, then
        // simply use the last line as it represents the last possible place
        // we can position to.
      
        Element map = doc.getDefaultRootElement();
        int fontHeight = metrics.getHeight();
        int lineIndex = (fontHeight > 0 ?
                            Math.abs((y - alloc.y) / fontHeight) :
                            map.getElementCount() - 1);
        if (lineIndex >= map.getElementCount()) {
            return getEndOffset() - 1;
        }
        Element line = map.getElement(lineIndex);
        int dx = 0;
        if (lineIndex == 0) {
            //alloc.x += firstLineOffset;
           // alloc.width -= firstLineOffset;
        }
        if (x < alloc.x) {
            // point is to the left of the line
            return line.getStartOffset();
        } else if (x > alloc.x + alloc.width) {
            // point is to the right of the line
            return line.getEndOffset() - 1;
        } else {
            // Determine the offset into the text
            try {
                int p0 = line.getStartOffset();
                int p1 = line.getEndOffset() - 1;
                Segment s = new Segment();
                doc.getText(p0, p1 - p0, s);
                int tabBase = alloc.x;
                int offs = p0 + UniTools.getTabbedTextOffset(s, metrics,
                                                              tabBase, x, this, p0);
                //SegmentCache.releaseSharedSegment(s);
                return offs;
            } catch (BadLocationException e) {
                // should not happen
                return -1;
            }
        }
    }
}
 
Example 20
Source Project: netbeans   File: DocUtils.java    License: 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);
}