javax.swing.text.Document#getLength ( )源码实例Demo

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

源代码1 项目: PacketProxy   文件: WrapEditorKit.java
@Override
public void write(Writer out, Document doc, int pos, int len) throws IOException, BadLocationException {
	if ((pos < 0) || ((pos + len) > doc.getLength())) {
		throw new BadLocationException("DefaultEditorKit.write", pos);
	}

	Segment data = new Segment();
	int nleft = len;
	int offs = pos;

	while (nleft > 0) {
		int n = Math.min(nleft, 4096);
		doc.getText(offs, n, data);
		out.write(data.array, data.offset, data.count);
		offs += n;
		nleft -= n;
	}
}
 
源代码2 项目: astor   文件: ConsoleTextArea.java
synchronized void returnPressed() {
    Document doc = getDocument();
    int len = doc.getLength();
    Segment segment = new Segment();
    try {
        doc.getText(outputMark, len - outputMark, segment);
    } catch(javax.swing.text.BadLocationException ignored) {
        ignored.printStackTrace();
    }
    if(segment.count > 0) {
        history.add(segment.toString());
    }
    historyIndex = history.size();
    inPipe.write(segment.array, segment.offset, segment.count);
    append("\n");
    outputMark = doc.getLength();
    inPipe.write("\n");
    inPipe.flush();
    console1.flush();
}
 
源代码3 项目: netbeans   文件: DocumentTesting.java
@Override
protected void run(Context context) throws Exception {
    Document doc = getDocument(context);
    int docLen = doc.getLength();
    if (docLen == 0)
        return; // Nothing to possibly remove
    Random random = context.container().random();
    int length;
    if (REMOVE_CHAR == name()) { // Just use ==
        length = 1;
    } else if (REMOVE_TEXT == name()) { // Just use ==
        Integer maxLength = (Integer) context.getPropertyOrNull(REMOVE_TEXT_MAX_LENGTH);
        if (maxLength == null)
            maxLength = Integer.valueOf(10);
        if (maxLength > docLen)
            maxLength = Integer.valueOf(docLen);
        length = random.nextInt(maxLength) + 1;
    } else {
        throw new IllegalStateException("Unexpected op name=" + name());
    }
    int offset = random.nextInt(docLen - length + 1);
    remove(context, offset, length);
}
 
源代码4 项目: JsDroidCmd   文件: ConsoleTextArea.java
synchronized void returnPressed() {
    Document doc = getDocument();
    int len = doc.getLength();
    Segment segment = new Segment();
    try {
        doc.getText(outputMark, len - outputMark, segment);
    } catch(javax.swing.text.BadLocationException ignored) {
        ignored.printStackTrace();
    }
    if(segment.count > 0) {
        history.add(segment.toString());
    }
    historyIndex = history.size();
    inPipe.write(segment.array, segment.offset, segment.count);
    append("\n");
    outputMark = doc.getLength();
    inPipe.write("\n");
    inPipe.flush();
    console1.flush();
}
 
源代码5 项目: netbeans   文件: CustomCodeView.java
private static int getLineCount(Document doc) {
    int length = doc.getLength();
    String text;
    int count = 0;
    try {
        text = doc.getText(0, length);
    } catch (BadLocationException ex) { // should not happen
        Exceptions.printStackTrace(ex);
        return -1;
    }
    for (int i=0; i < length; i++) {
        if (text.charAt(i) == '\n') {
            count++;
        }
    }
    return count;
}
 
源代码6 项目: netbeans   文件: ModificationResult.java
private static void processDocumentLocked(Document doc, Difference diff) throws BadLocationException {
    switch (diff.getKind()) {
        case INSERT:
            doc.insertString(diff.getStartPosition().getOffset(), diff.getNewText(), null);
            break;
        case REMOVE:
            doc.remove(diff.getStartPosition().getOffset(), diff.getEndPosition().getOffset() - diff.getStartPosition().getOffset());
            break;
        case CHANGE: {
            // first insert the new content, THEN remove the old one. In situations where the content AFTER the
            // change is not writable this ordering allows to replace the content, but if we first delete, 
            // replacement cannot be inserted into the nonwritable area.
            int offs = diff.getStartPosition().getOffset();
            int removeLen = diff.getEndPosition().getOffset() - offs;
            
            // [NETBEANS-4270] Can't use "delta = diff.getNewText().length()".
            // doc.insertString may filter chars, e.g. '\r', and change length.
            int initialLength = doc.getLength();
            doc.insertString(offs, diff.getNewText(), null);
            int delta = doc.getLength() - initialLength;
            doc.remove(delta + offs, removeLen);
            break;
        }
    }
}
 
源代码7 项目: netbeans   文件: DocumentUtilities.java
/**
 * Get string representation of an offset for debugging purposes
 * in form "offset[line:column]". Both lines and columns start counting from 1
 * like in the editor's status bar. Tabs are expanded when counting the column.
 *
 * @param sb valid string builder to which text will be appended or null in which case
 *  the method itself will create a string builder and it will return it.
 * @param doc non-null document in which the offset is located.
 * @param offset offset in the document.
 * @return non-null string builder to which the description was added.
 * @since 1.27
 */
public static StringBuilder appendOffset(StringBuilder sb, Document doc, int offset) {
    if (sb == null) {
        sb = new StringBuilder(50);
    }
    sb.append(offset).append('[');
    if (offset < 0) { // Offset too low
        sb.append("<0");
    } else if (offset > doc.getLength() + 1) { // +1 for AbstractDocument-based docs
        sb.append(">").append(doc.getLength());
    } else { // Valid offset
        Element paragraphRoot = getParagraphRootElement(doc);
        int lineIndex = paragraphRoot.getElementIndex(offset);
        Element lineElem = paragraphRoot.getElement(lineIndex);
        sb.append(lineIndex + 1).append(':'); // Line
        sb.append(visualColumn(doc, lineElem.getStartOffset(), offset) + 1); // Column
    }
    sb.append(']');
    return sb;
}
 
源代码8 项目: netbeans   文件: WordMatchTest.java
public void testOffsetDocLenBackward() throws Exception {
    Document doc = new PlainDocument();
    WordMatch wordMatch = WordMatch.get(doc);
    //                   012345678901234567890123456789
    doc.insertString(0, "abc abc dab ab a", null);
    int docLen = doc.getLength();
    wordMatch.matchWord(docLen, false);
    compareText(doc, docLen - 1, "ab", docLen + 1);
    wordMatch.matchWord(docLen, false);
    compareText(doc, docLen - 1, "abc", docLen + 2);
    wordMatch.matchWord(docLen, false);
    compareText(doc, docLen - 1, "abc", docLen + 2);

    wordMatch.matchWord(docLen, true);
    compareText(doc, docLen - 1, "ab", docLen + 1);
    wordMatch.matchWord(docLen, true);
    compareText(doc, docLen - 1, "a", docLen);
}
 
源代码9 项目: rapidminer-studio   文件: TextActions.java
@Override
public void actionPerformed(ActionEvent e) {
	JTextComponent target = getTextComponent(e);
	boolean beep = true;
	if ((target != null) && (target.isEditable())) {
		try {
			Document doc = target.getDocument();
			int ss = 0;
			int se = doc.getLength();

			if (ss != se) {
				doc.remove(ss, se - ss);
				beep = false;
			}
		} catch (BadLocationException bl) {
		}
	}
	if (beep) {
		UIManager.getLookAndFeel().provideErrorFeedback(target);
	}
}
 
源代码10 项目: jpexs-decompiler   文件: LineMarkedEditorPane.java
public Token tokenAtPos(Point lastPos) {
    Document d = getDocument();
    if (d instanceof SyntaxDocument) {
        SyntaxDocument sd = (SyntaxDocument) d;

        //correction of token last character
        int pos = viewToModel(lastPos);
        Rectangle r;
        try {
            r = modelToView(pos);
            if (r != null) {
                if (lastPos.x < r.x) {
                    pos--;
                }
            }
        } catch (BadLocationException ex) {
            //ignore
        }
        Token t = sd.getTokenAt(pos);

        //Correction of token of length 1 character
        if (pos > 0 && pos < d.getLength() - 1 && t != null && t.length == 1) {
            Token tprev = sd.getTokenAt(pos - 1);
            if (tprev == t) {
                t = sd.getTokenAt(pos + 1);
            }
        }

        return t;
    }
    return null;
}
 
源代码11 项目: FlatLaf   文件: FlatCaret.java
protected void selectAllOnFocusGained() {
	JTextComponent c = getComponent();
	Document doc = c.getDocument();
	if( doc == null || !c.isEnabled() || !c.isEditable() )
		return;

	Object selectAllOnFocusPolicy = c.getClientProperty( SELECT_ALL_ON_FOCUS_POLICY );
	if( selectAllOnFocusPolicy == null )
		selectAllOnFocusPolicy = this.selectAllOnFocusPolicy;

	if( SELECT_ALL_ON_FOCUS_POLICY_NEVER.equals( selectAllOnFocusPolicy ) )
		return;

	if( !SELECT_ALL_ON_FOCUS_POLICY_ALWAYS.equals( selectAllOnFocusPolicy ) ) {
		// policy is "once" (or null or unknown)

		// was already focused?
		if( wasFocused )
			return;

		// check whether selection was modified before gaining focus
		int dot = getDot();
		int mark = getMark();
		if( dot != mark || dot != doc.getLength() )
			return;
	}

	// select all
	if( c instanceof JFormattedTextField ) {
		EventQueue.invokeLater( () -> {
			setDot( 0 );
			moveDot( doc.getLength() );
		} );
	} else {
		setDot( 0 );
		moveDot( doc.getLength() );
	}
}
 
源代码12 项目: xdm   文件: NewDownloadWindow.java
void update(DocumentEvent e) {
	try {
		Document doc = e.getDocument();
		int len = doc.getLength();
		String text = doc.getText(0, len);
		filePane.setFileName(XDMUtils.getFileName(text));
	} catch (Exception err) {
		Logger.log(err);
	}
}
 
private boolean refactorToStyleSheet(ModificationResult modificationResult, RefactoringContext context) {
    Document extSheetDoc = GsfUtilities.getDocument(refactoring.getExternalSheet(), true);

    int insertOffset = extSheetDoc.getLength();
    int baseIndent = getPreviousLineIndent(extSheetDoc, insertOffset);

    return refactorToEmbeddedSection(modificationResult, context, refactoring.getExternalSheet(),
            insertOffset, baseIndent, null, null);
}
 
源代码14 项目: bigtable-sql   文件: MessagePanel.java
/**
 * Do the real appending of text to the message panel. The last message is always highlighted.
 * @todo Highlight not only the last message, but all messages from SQL statements which were run together.
 *
 * @param string	The String to be appended.
 * @param saSet		The SimpleAttributeSet to be used for for the string.
 */
private void append(String string, SimpleAttributeSet saSet)
{
	Document document = getStyledDocument();
	try
	{
        /////////////////////////////////////////////////////////////////////////////////
        // Checks if the former message should be highlighted in a 'history' color.
        if (document.getLength() >= _lastLength && null != _lastMessage)
		{
           SimpleAttributeSet historySaSet = _saSetHistoryBySaSet.get(_lastSASet);
           document.remove(_lastLength, _lastMessage.length());
           document.insertString(document.getLength(), _lastMessage, historySaSet);
		}
        //
        ///////////////////////////////////////////////////////////////////////////////////

        _lastLength = document.getLength();
		_lastMessage = string;
		_lastSASet = saSet;

		document.insertString(document.getLength(), string, saSet);
	}
	catch (BadLocationException ble)
	{
		s_log.error("Error appending text to MessagePanel document.", ble);
	}
}
 
源代码15 项目: java-swing-tips   文件: MainPanel.java
@Override public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
  Document doc = fb.getDocument();
  int currentLength = doc.getLength();
  String currentContent = doc.getText(0, currentLength);
  String before = currentContent.substring(0, offset);
  String after = currentContent.substring(length + offset, currentLength);
  String newValue = before + Objects.toString(text, "") + after;
  checkInput(newValue, offset);
  fb.replace(offset, length, text, attrs);
}
 
源代码16 项目: netbeans   文件: EditorProvider.java
@Override
    protected JComponent getComponent() {
        JTextComponent text = getTextComponent();

        if (text == null) {
            return null;
        }
        if (Config.getDefault().isAsEditor()) {
            return getEditorComponent(text);
        }
        Document document = myEditor.getDocument();

        if (document == null) {
            return null;
        }
        int start;
        int end;

        if (Config.getDefault().isSelection()) {
            start = text.getSelectionStart();
            end = text.getSelectionEnd();
        }
        else {
            start = 0;
            end = document.getLength();
        }
        AttributedCharacterIterator[] iterators = getIterators(document, start, end);
//out();
//out("iterators: " + iterators);
//out();
        if (iterators != null) {
            return new ComponentDocument(iterators);
        }
        try {
            return new ComponentDocument(text.getText(start, end - start));
        }
        catch (BadLocationException e) {
            return null;
        }
    }
 
源代码17 项目: netbeans   文件: JaxWsCodeGenerator.java
public static void insertMethodCall(InvokeOperationCookie.TargetSourceType targetSourceType,
        DataObject dataObj, Lookup sourceNodeLookup) {

    EditorCookie cookie = dataObj.getCookie(EditorCookie.class);
    OperationNode opNode = sourceNodeLookup.lookup(OperationNode.class);
    boolean inJsp = InvokeOperationCookie.TargetSourceType.JSP == targetSourceType;
    Node portNode = opNode.getParentNode();
    Node serviceNode = portNode.getParentNode();
    addProjectReference(serviceNode, dataObj);
    final Document document;
    int position = -1;
    if (inJsp) {
        //TODO:
        //this should be handled differently, see issue 60609
        document = cookie.getDocument();
        try {
            String content = document.getText(0, document.getLength());
            position = content.lastIndexOf("</body>"); //NOI18N
            if (position < 0) {
                position = content.lastIndexOf("</html>"); //NOI18N
            }
            if (position >= 0) { //find where line begins
                while (position > 0 && content.charAt(position - 1) != '\n' && content.charAt(position - 1) != '\r') {
                    position--;
                }
            } else {
                position = document.getLength();
            }
        } catch (BadLocationException ble) {
            Exceptions.printStackTrace(ble);
        }
    } else {
        EditorCookie ec = dataObj.getCookie(EditorCookie.class);
        JEditorPane pane = ec.getOpenedPanes()[0];
        document = pane.getDocument();
        position = pane.getCaretPosition();
    }
    final int pos = position;
    insertMethod(document, pos, opNode);
}
 
源代码18 项目: netbeans   文件: DrawEngineTest.java
private void checkViewToModelConsistency(JEditorPane jep) throws Exception {
        Document doc = jep.getDocument();
        
        assertTrue("Expecting BaseTextUI", jep.getUI() instanceof BaseTextUI);
        BaseTextUI btui = (BaseTextUI) jep.getUI();
        Insets margin = btui.getEditorUI().getTextMargin();
        int charWidth = btui.getEditorUI().defaultSpaceWidth;
        int charHeight = btui.getEditorUI().getLineHeight();

//        System.out.println("### charWidth = " + charWidth + ", charHeight = " + charHeight
//            + ", docLen = " + doc.getLength()
//            + ", jep.width = " + jep.getWidth()
//            + ", jep.height = " + jep.getHeight());
        
        Rectangle eodRectangle = null;
        Rectangle eolRectangle = null;
        for(int y = charHeight / 2 + margin.top; y < jep.getHeight(); y += charHeight) {
            if (eodRectangle == null) {
                eolRectangle = null;
            }
            for(int x = charWidth / 2 + margin.left; x < jep.getWidth(); x += charWidth) {
                Point p = new Point(x, y);

                // view-to-model translation
                int offset = jep.viewToModel(p);
                assertTrue("Invalid v2m translation: " + s(p) + " -> " + offset+ ", docLen = " + doc.getLength(),
                        offset >= 0 && offset <= doc.getLength());
                
                // model-to-view
                Rectangle r = jep.modelToView(offset);
                assertNotNull("No m2v translation: offset = " + offset + ", docLen = " + doc.getLength(), r);

                // check
                if (eodRectangle == null) {
                    boolean eod = offset == doc.getLength();
                    boolean eol = doc.getText(offset, 1).charAt(0) == '\n';
                    
                    if (eolRectangle == null) {
                        assertTrue("Inconsistent v2m-m2v translation, point = " + s(p) + " not within " + s(r)
                            + ", offset = " + offset + ", docLen = " + doc.getLength(), r.contains(p));
                        if (eol) {
                            eolRectangle = r;
                        }
                    } else {
                        assertEquals("Inconsistent v2m-m2v translation, for point = " + s(p) + " behing eol"
                            + ", offset = " + offset + ", docLen = " + doc.getLength(), eolRectangle, r);
                    }
                    
                    if (eod) {
                        eodRectangle = r;
                    }
                } else {
                    Point pointAtTheLastLine = new Point(Math.min(p.x, eolRectangle.x), eodRectangle.y);
                    assertTrue("Inconsistent v2m-m2v translation, for point = " + s(p)
                        + " behing eod, point at the last line " + s(pointAtTheLastLine) + " is outside of " + s(r)
                        + ", offset = " + offset + ", docLen = " + doc.getLength(), r.contains(pointAtTheLastLine));
                }
            }
        }
    }
 
源代码19 项目: netbeans   文件: ParagraphViewChildren.java
private int viewToModelWithAmbiguousWrapLineCaretAdustment(
        double x, double y, IndexAndAlloc indexAndAlloc, Bias[] biasRet)
{
    final EditorView view = indexAndAlloc.viewOrPart;
    int ret = view.viewToModelChecked(x, y, indexAndAlloc.alloc, biasRet);
    /* NETBEANS-980: On wrap lines, the caret offset that corresponds to "right after the last
    character on the current wrap line" is ambiguous, because it can equivalently be interpreted
    as "right before the first character on the following wrap line" (because there is no explicit
    newline character to increment the offset around). The NetBeans EditorKit uses the latter
    interpretation when painting the caret and calculating visual positions via modelToView. Here,
    in viewToModel, we need to ensure that the returned offset always corresponds to a caret on
    the wrap line with the given Y position. Otherwise, keyboard actions such as UpAction,
    DownAction, and EndLineAction (in o.n.editor.BaseKit), or clicking the mouse in the area to
    the right of the end of the wrap line, will not work correctly.

    The approach here is to map the end of the wrap line to a caret position right _before_ the
    last character on the wrap line. Under word wrapping, said character will usually be a space
    (or a hyphen; see NETBEANS-977). This is the same approach as is taken in JTextArea with word
    wrapping enabled. The latter can be confirmed by entering a very long word in a word-wrapping
    JTextArea so that the last character on the wrap line is a letter rather than a space, and
    pressing the "End" key (Command+Right Arrow on Mac); the caret will end up right before the
    last character on the wrap line. Other approaches are possible, such as relying on the caret
    bias to differentiate the ambigous offsets, but the approach here seemed like the simplest
    one to implement. */
    if (isWrapped() && view.getLength() > 0 && ret >= view.getEndOffset()) {
        /* As a small improvement, avoid applying the adjustment on the very last wrap line of a
        paragraph, where it is not needed, and where the last character is likely to be something
        other than a space. This adjustment ensures that the caret ends up in the expected place
        if the user clicks on the right-hand half of the last character on the wrap line. (If the
        user clicks _beyond_ the last character of the last wrap line, hit testing would encounter
        a NewlineView instead of a HighlightsViewPart, which would yield the correct caret
        position in any case.) */
        boolean isLastWrapLineInParagraph = false;
        try {
            final Document doc = view.getDocument();
            if (ret < doc.getLength())
                isLastWrapLineInParagraph = view.getDocument().getText(ret, 1).equals("\n");
        } catch (BadLocationException e) {
            // Ignore.
        }
        if (!isLastWrapLineInParagraph)
            ret = view.getEndOffset() - 1;
    }
    return ret;
}
 
源代码20 项目: netbeans   文件: GsfCompletionProvider.java
/**
 * 
 * @param upToOffset If set, complete only up to the given caret offset, otherwise complete
 *   the full symbol at the offset
 */
private Env getCompletionEnvironment(ParserResult controller, boolean upToOffset)
    throws IOException {
    // If you invoke code completion while indexing is in progress, the
    // completion job (which stores the caret offset) will be delayed until
    // indexing is complete - potentially minutes later. When the job
    // is finally run we need to make sure the caret position is still valid. (93017)
    Document doc = controller.getSnapshot ().getSource ().getDocument (false);
    int length = doc != null ? doc.getLength() : (int)controller.getSnapshot ().getSource ().getFileObject().getSize();
    if (caretOffset > length) {
        caretOffset = length;
    }
    
    int offset = caretOffset;
    String prefix = null;

    // 
    // TODO - handle the upToOffset parameter
    // Look at the parse tree, and find the corresponding end node
    // offset...
    
    CodeCompletionHandler completer = getCompletable(controller);
    try {
        // TODO: use the completion helper to get the contxt
        if (completer != null && offset != -1) {
            prefix = completer.getPrefix(controller, offset, upToOffset);
        }
        if (prefix == null && doc != null) {
            int[] blk =
                org.netbeans.editor.Utilities.getIdentifierBlock((BaseDocument)doc,
                    offset);

            if (blk != null) {
                int start = blk[0];

                if (start < offset ) {
                    if (upToOffset) {
                        prefix = doc.getText(start, offset - start);
                    } else {
                        prefix = doc.getText(start, blk[1]-start);
                    }
                }
            }
        }
    } catch (BadLocationException ex) {
        ErrorManager.getDefault().notify(ex);
    }
    
    return new Env(offset, prefix, controller, completer);
}