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

The following examples show how to use javax.swing.text.Document#getDefaultRootElement() . 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: MainPanel.java    From java-swing-tips with 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 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: MITextEditorPane.java    From MeteoInfo with GNU Lesser General Public License v3.0 6 votes vote down vote up
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 4
Source File: NbEditorUtilities.java    From netbeans with 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 5
Source File: MainPanel.java    From java-swing-tips with 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 6
Source File: BookmarkUtils.java    From netbeans with 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 7
Source File: FoldView.java    From netbeans with 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 8
Source File: LockView.java    From netbeans with 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 9
Source File: GotoLineOrBookmarkPanel.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * 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 File: LimitLinesDocumentListener.java    From eml-to-pdf-converter with Apache License 2.0 5 votes vote down vote up
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 11
Source File: BookmarksPersistenceTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private int getLineIndex(Document doc, int offset) {
    Element root = doc.getDefaultRootElement();
    return root.getElementIndex(offset);
}
 
Example 12
Source File: SyntaxView.java    From jpexs-decompiler with GNU General Public License v3.0 4 votes vote down vote up
@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 13
Source File: BookmarkUtils.java    From netbeans with 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 14
Source File: AndroidGradleDependencyUpdater.java    From NBANDROID-V2 with Apache License 2.0 4 votes vote down vote up
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 15
Source File: EditorCaret.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 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 16
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 17
Source File: FixLineSyntaxState.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private static Element getLineRoot(Document doc) {
    return doc.getDefaultRootElement();
}
 
Example 18
Source File: GetJavaWord.java    From netbeans with 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 19
Source File: AnimationAutoCompletion.java    From 3Dscript with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Override
int getLineOfCaret() {
	Document doc = textComponent.getDocument();
	Element root = doc.getDefaultRootElement();
	return root.getElementIndex(textComponent.getCaretPosition());
}
 
Example 20
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);
}