javax.swing.JEditorPane#getCaret ( )源码实例Demo

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

源代码1 项目: netbeans   文件: ToggleBlockCommentActionTest.java
protected void testCursorInFile(String file) throws Exception {
    FileObject fo = getTestFile(file);
    assertNotNull(fo);
    String source = readFile(fo);

    int sourcePos = source.indexOf('^');
    assertNotNull(sourcePos);
    String sourceWithoutMarker = source.substring(0, sourcePos) + source.substring(sourcePos+1);

    JEditorPane ta = getPane(sourceWithoutMarker);
    Caret caret = ta.getCaret();
    caret.setDot(sourcePos);
    BaseDocument doc = (BaseDocument) ta.getDocument();

    Action a = new ToggleBlockCommentAction();
    a.actionPerformed(new ActionEvent(ta, 0, null));

    doc.getText(0, doc.getLength());
    doc.insertString(caret.getDot(), "^", null);

    String target = doc.getText(0, doc.getLength());
    assertDescriptionMatches(file, target, false, ".toggleComment");
}
 
源代码2 项目: netbeans   文件: ToggleBlockCommentActionTest.java
protected void testInFile(String file) throws Exception {
    FileObject fo = getTestFile(file);
    assertNotNull(fo);
    String source = readFile(fo);

    int sourcePos = source.indexOf('^');
    assertNotNull(sourcePos);
    String sourceWithoutMarker = source.substring(0, sourcePos) + source.substring(sourcePos+1);

    JEditorPane ta = getPane(sourceWithoutMarker);
    Caret caret = ta.getCaret();
    caret.setDot(sourcePos);
    BaseDocument doc = (BaseDocument) ta.getDocument();

    Action a = new ToggleBlockCommentAction();
    a.actionPerformed(new ActionEvent(ta, 0, null));

    doc.getText(0, doc.getLength());
    doc.insertString(caret.getDot(), "^", null);

    String target = doc.getText(0, doc.getLength());
    assertDescriptionMatches(file, target, false, ".toggleComment");
}
 
源代码3 项目: netbeans   文件: EditorContextImpl.java
/**
 * Returns identifier currently selected in editor or <code>null</code>.
 *
 * @return identifier currently selected in editor or <code>null</code>
 */
@Override
public String getSelectedIdentifier () {
    JEditorPane ep = contextDispatcher.getCurrentEditor ();
    if (ep == null) {
        return null;
    }
    Caret caret = ep.getCaret();
    if (caret == null) {
        // No caret => no selected text
        return null;
    }
    String s = ep.getSelectedText ();
    if (s == null) {
        return null;
    }
    if (Utilities.isJavaIdentifier (s)) {
        return s;
    }
    return null;
}
 
源代码4 项目: netbeans   文件: EditorContextDispatcher.java
/**
 * Get the line of the caret in the most recent editor.
 * This returns the current line in the current editor if there's one,
 * or a line of the caret in the editor, that was most recently active.
 * @return the line or <code>null</code> when there was no recent active editor.
 */
public Line getMostRecentLine() {
    EditorCookie e = getMostRecentEditorCookie ();
    if (e == null) return null;
    JEditorPane ep = getMostRecentEditor ();
    if (ep == null) return null;
    StyledDocument d = e.getDocument ();
    if (d == null) return null;
    Caret caret = ep.getCaret ();
    if (caret == null) return null;
    int lineNumber = NbDocument.findLineNumber(d, caret.getDot());
    Line.Set lineSet = e.getLineSet();
    try {
        return lineSet.getCurrent(lineNumber);
    } catch (IndexOutOfBoundsException ex) {
        return null;
    }
}
 
源代码5 项目: jdk1.8-source-analysis   文件: StyledEditorKit.java
/**
 * Called when the kit is being installed into
 * a JEditorPane.
 *
 * @param c the JEditorPane
 */
public void install(JEditorPane c) {
    c.addCaretListener(inputAttributeUpdater);
    c.addPropertyChangeListener(inputAttributeUpdater);
    Caret caret = c.getCaret();
    if (caret != null) {
        inputAttributeUpdater.updateInputAttributes
                              (caret.getDot(), caret.getMark(), c);
    }
}
 
源代码6 项目: jdk8u60   文件: StyledEditorKit.java
/**
 * Called when the kit is being installed into
 * a JEditorPane.
 *
 * @param c the JEditorPane
 */
public void install(JEditorPane c) {
    c.addCaretListener(inputAttributeUpdater);
    c.addPropertyChangeListener(inputAttributeUpdater);
    Caret caret = c.getCaret();
    if (caret != null) {
        inputAttributeUpdater.updateInputAttributes
                              (caret.getDot(), caret.getMark(), c);
    }
}
 
源代码7 项目: JDKSourceCode1.8   文件: StyledEditorKit.java
/**
 * Called when the kit is being installed into
 * a JEditorPane.
 *
 * @param c the JEditorPane
 */
public void install(JEditorPane c) {
    c.addCaretListener(inputAttributeUpdater);
    c.addPropertyChangeListener(inputAttributeUpdater);
    Caret caret = c.getCaret();
    if (caret != null) {
        inputAttributeUpdater.updateInputAttributes
                              (caret.getDot(), caret.getMark(), c);
    }
}
 
源代码8 项目: netbeans   文件: EditorContextImpl.java
/**
 * Returns number of line currently selected in editor or <code>-1</code>.
 *
 * @return number of line currently selected in editor or <code>-1</code>
 */
public int getCurrentOffset () {
    JEditorPane ep = contextDispatcher.getCurrentEditor();
    if (ep == null) {
        return -1;
    }
    Caret caret = ep.getCaret ();
    if (caret == null) {
        return -1;
    }
    return caret.getDot();
}
 
源代码9 项目: netbeans   文件: ToggleBlockCommentActionTest.java
protected void testSelectionInFile(String file) throws Exception {
    FileObject fo = getTestFile(file);
    assertNotNull(fo);
    String source = readFile(fo);

    int sourcePosStart = source.indexOf('^');
    assertNotNull(sourcePosStart);
    int sourcePosEnd = source.lastIndexOf('^');
    assertNotNull(sourcePosEnd);
    String sourceWithoutMarkers = source.substring(0, sourcePosStart) + source.substring(sourcePosStart + 1, sourcePosEnd) + source.substring(sourcePosEnd + 1);

    JEditorPane ta = getPane(sourceWithoutMarkers);
    Caret caret = ta.getCaret();
    caret.setDot(sourcePosStart);
    ta.setSelectionStart(sourcePosStart);
    ta.setSelectionEnd(sourcePosEnd - 1);
    BaseDocument doc = (BaseDocument) ta.getDocument();

    Action a = new ToggleBlockCommentAction();
    a.actionPerformed(new ActionEvent(ta, 0, null));

    doc.getText(0, doc.getLength());
    doc.insertString(caret.getDot(), "^", null);

    String target = doc.getText(0, doc.getLength());
    assertDescriptionMatches(file, target, false, ".toggleComment");
}
 
源代码10 项目: netbeans   文件: PhpCommentGeneratorTest.java
@Override
public void insertNewline(String source, String reformatted, IndentPrefs preferences) throws Exception {
    int sourcePos = source.indexOf('^');
    assertNotNull(sourcePos);
    source = source.substring(0, sourcePos) + source.substring(sourcePos + 1);
    Formatter formatter = getFormatter(null);

    int reformattedPos = reformatted.indexOf('^');
    assertNotNull(reformattedPos);
    reformatted = reformatted.substring(0, reformattedPos) + reformatted.substring(reformattedPos + 1);

    JEditorPane ta = getPane(source);
    Caret caret = ta.getCaret();
    caret.setDot(sourcePos);
    BaseDocument doc = (BaseDocument) ta.getDocument();
    if (formatter != null) {
        configureIndenters(doc, formatter, true);
    }

    setupDocumentIndentation(doc, preferences);

    runKitAction(ta, DefaultEditorKit.insertBreakAction, "\n");

    // wait for generating comment
    Future<?> future = PhpCommentGenerator.RP.submit(new Runnable() {
        @Override
        public void run() {
        }
    });
    future.get();

    String formatted = doc.getText(0, doc.getLength());
    assertEquals(reformatted, formatted);

    if (reformattedPos != -1) {
        assertEquals(reformattedPos, caret.getDot());
    }
}
 
源代码11 项目: jdk8u-jdk   文件: StyledEditorKit.java
/**
 * Called when the kit is being installed into
 * a JEditorPane.
 *
 * @param c the JEditorPane
 */
public void install(JEditorPane c) {
    c.addCaretListener(inputAttributeUpdater);
    c.addPropertyChangeListener(inputAttributeUpdater);
    Caret caret = c.getCaret();
    if (caret != null) {
        inputAttributeUpdater.updateInputAttributes
                              (caret.getDot(), caret.getMark(), c);
    }
}
 
源代码12 项目: netbeans   文件: JadeIndenterTest.java
private void testIndentInFile(String file, IndentPrefs indentPrefs, int initialIndent) throws Exception {
    FileObject fo = getTestFile(file);
    assertNotNull(fo);
    String source = readFile(fo);

    int sourcePos = source.indexOf('^');
    assertNotNull(sourcePos);
    String sourceWithoutMarker = source.substring(0, sourcePos) + source.substring(sourcePos + 1);
    Formatter formatter = getFormatter(indentPrefs);

    JEditorPane ta = getPane(sourceWithoutMarker);
    Caret caret = ta.getCaret();
    caret.setDot(sourcePos);
    BaseDocument doc = (BaseDocument) ta.getDocument();
    if (formatter != null) {
        configureIndenters(doc, formatter, true);
    }

    setupDocumentIndentation(doc, indentPrefs);

    runKitAction(ta, DefaultEditorKit.insertBreakAction, "\n");

    doc.getText(0, doc.getLength());
    doc.insertString(caret.getDot(), "^", null);

    String target = doc.getText(0, doc.getLength());
    assertDescriptionMatches(file, target, false, ".indented");
}
 
源代码13 项目: netbeans   文件: JsCommentGeneratorEmbeddedTest.java
@Override
public void insertNewline(String source, String reformatted, IndentPrefs preferences) throws Exception {
    int sourcePos = source.indexOf('^');
    assertNotNull(sourcePos);
    source = source.substring(0, sourcePos) + source.substring(sourcePos + 1);
    Formatter formatter = getFormatter(null);

    int reformattedPos = reformatted.indexOf('^');
    assertNotNull(reformattedPos);
    reformatted = reformatted.substring(0, reformattedPos) + reformatted.substring(reformattedPos + 1);

    JEditorPane ta = getPane(source);
    Caret caret = ta.getCaret();
    caret.setDot(sourcePos);
    BaseDocument doc = (BaseDocument) ta.getDocument();
    if (formatter != null) {
        configureIndenters(doc, formatter, true);
    }

    setupDocumentIndentation(doc, preferences);

    runKitAction(ta, DefaultEditorKit.insertBreakAction, "\n");

    // wait for generating comment
    Future<?> future = JsDocumentationCompleter.RP.submit(new Runnable() {
        @Override
        public void run() {
        }
    });
    future.get();

    String formatted = doc.getText(0, doc.getLength());
    assertEquals(reformatted, formatted);

    if (reformattedPos != -1) {
        assertEquals(reformattedPos, caret.getDot());
    }
}
 
源代码14 项目: netbeans   文件: JsCommentGeneratorTest.java
@Override
public void insertNewline(String source, String reformatted, IndentPrefs preferences) throws Exception {
    int sourcePos = source.indexOf('^');
    assertNotNull(sourcePos);
    source = source.substring(0, sourcePos) + source.substring(sourcePos + 1);
    Formatter formatter = getFormatter(null);

    int reformattedPos = reformatted.indexOf('^');
    assertNotNull(reformattedPos);
    reformatted = reformatted.substring(0, reformattedPos) + reformatted.substring(reformattedPos + 1);

    JEditorPane ta = getPane(source);
    Caret caret = ta.getCaret();
    caret.setDot(sourcePos);
    BaseDocument doc = (BaseDocument) ta.getDocument();
    if (formatter != null) {
        configureIndenters(doc, formatter, true);
    }

    setupDocumentIndentation(doc, preferences);

    runKitAction(ta, DefaultEditorKit.insertBreakAction, "\n");

    // wait for generating comment
    Future<?> future = JsDocumentationCompleter.RP.submit(new Runnable() {
        @Override
        public void run() {
        }
    });
    future.get();

    String formatted = doc.getText(0, doc.getLength());
    assertEquals(reformatted, formatted);

    if (reformattedPos != -1) {
        assertEquals(reformattedPos, caret.getDot());
    }
}
 
源代码15 项目: jdk8u-dev-jdk   文件: StyledEditorKit.java
/**
 * Called when the kit is being installed into
 * a JEditorPane.
 *
 * @param c the JEditorPane
 */
public void install(JEditorPane c) {
    c.addCaretListener(inputAttributeUpdater);
    c.addPropertyChangeListener(inputAttributeUpdater);
    Caret caret = c.getCaret();
    if (caret != null) {
        inputAttributeUpdater.updateInputAttributes
                              (caret.getDot(), caret.getMark(), c);
    }
}
 
源代码16 项目: netbeans   文件: WatchPanel.java
public static int getRecentColumn() {
    JEditorPane mostRecentEditor = EditorContextDispatcher.getDefault().getMostRecentEditor();
    if (mostRecentEditor != null) {
        Caret caret = mostRecentEditor.getCaret();
        if (caret != null) {
            int offset = caret.getDot();
            try {
                int rs = javax.swing.text.Utilities.getRowStart(mostRecentEditor, offset);
                return offset - rs;
            } catch (BadLocationException blex) {}
        }
    }
    return 0;
}
 
源代码17 项目: netbeans   文件: ToolTipAnnotation.java
private String getSelectedText(JEditorPane pane, int offset) {
    if (pane != null
            && pane.getCaret() != null
            && pane.getSelectionStart() <= offset
            && offset <= pane.getSelectionEnd()) {
        return pane.getSelectedText();
    }
    return null;
}
 
源代码18 项目: netbeans   文件: PHPNewLineIndenterTest.java
protected void testIndentInFile(String file, IndentPrefs indentPrefs, int initialIndent) throws Exception {
    FileObject fo = getTestFile(file);
    assertNotNull(fo);
    String source = readFile(fo);

    int sourcePos = source.indexOf('^');
    assertNotNull(sourcePos);
    String sourceWithoutMarker = source.substring(0, sourcePos) + source.substring(sourcePos+1);
    Formatter formatter = getFormatter(indentPrefs);

    JEditorPane ta = getPane(sourceWithoutMarker);
    Caret caret = ta.getCaret();
    caret.setDot(sourcePos);
    BaseDocument doc = (BaseDocument) ta.getDocument();
    if (formatter != null) {
        configureIndenters(doc, formatter, true);
    }

    setupDocumentIndentation(doc, indentPrefs);


    Map<String, Object> options = new HashMap<String, Object>(FmtOptions.getDefaults());
    options.put(FmtOptions.INITIAL_INDENT, initialIndent);
    if (indentPrefs != null) {
        options.put(FmtOptions.INDENT_SIZE, indentPrefs.getIndentation());
    }
    Preferences prefs = CodeStylePreferences.get(doc).getPreferences();
    for (String option : options.keySet()) {
        Object value = options.get(option);
        if (value instanceof Integer) {
            prefs.putInt(option, ((Integer) value).intValue());
        } else if (value instanceof String) {
            prefs.put(option, (String) value);
        } else if (value instanceof Boolean) {
            prefs.put(option, ((Boolean) value).toString());
        } else if (value instanceof CodeStyle.BracePlacement) {
            prefs.put(option, ((CodeStyle.BracePlacement) value).name());
        } else if (value instanceof CodeStyle.WrapStyle) {
            prefs.put(option, ((CodeStyle.WrapStyle) value).name());
        }
    }

    runKitAction(ta, DefaultEditorKit.insertBreakAction, "\n");

    doc.getText(0, doc.getLength());
    doc.insertString(caret.getDot(), "^", null);

    String target = doc.getText(0, doc.getLength());
    assertDescriptionMatches(file, target, false, ".indented");
}
 
源代码19 项目: netbeans   文件: CloneableEditorSupport.java
/** Forcibly create one editor component. Then set the caret
* to the given position.
* @param pos where to place the caret
* @param column where to place the caret
* @param reuse if true, the infrastructure tries to reuse other, already opened editor
 * for the purpose of opening this file/line. 
* @return always non-<code>null</code> editor
*/
private final Pane openAtImpl(final PositionRef pos, final int column, boolean reuse) {
    CloneableEditorSupport redirect = CloneableEditorSupportRedirector.findRedirect(this);
    if (redirect != null) {
        return redirect.openAtImpl(pos, column, reuse);
    }
    final Pane e = openPane(reuse);
    final Task t = prepareDocument();
    e.ensureVisible();
    class Selector implements TaskListener, Runnable {
        private boolean documentLocked = false;

        public void taskFinished(org.openide.util.Task t2) {
            javax.swing.SwingUtilities.invokeLater(this);
            t2.removeTaskListener(this);
        }

        public void run() {
            // #25435. Pane can be null.
            JEditorPane ePane = e.getEditorPane();

            if (ePane == null) {
                return;
            }

            StyledDocument doc = getDocument();

            if (doc == null) {
                return; // already closed or error loading
            }

            if (!documentLocked) {
                documentLocked = true;
                doc.render(this);
            } else {
                Caret caret = ePane.getCaret();

                if (caret == null) {
                    return;
                }

                int offset;

                // Pane's document may differ - see #204980
                Document paneDoc = ePane.getDocument();
                if (paneDoc instanceof StyledDocument && paneDoc != doc) {
                    if (ERR.isLoggable(Level.FINE)) {
                        ERR.fine("paneDoc=" + paneDoc + "\n !=\ndoc=" + doc); // NOI18N
                    }
                    doc = (StyledDocument) paneDoc;
                }

                javax.swing.text.Element el = NbDocument.findLineRootElement(doc);
                el = el.getElement(el.getElementIndex(pos.getOffset()));
                offset = el.getStartOffset() + Math.max(0, column);

                if (offset > el.getEndOffset()) {
                    offset = Math.max(el.getStartOffset(), el.getEndOffset() - 1);
                }

                caret.setDot(offset);

                try { // scroll to show reasonable part of the document
                    Rectangle r = ePane.modelToView(offset);
                    if (r != null) {
                        r.height *= 5;
                        ePane.scrollRectToVisible(r);
                    }
                } catch (BadLocationException ex) {
                    ERR.log(Level.WARNING, "Can't scroll to text: pos.getOffset=" + pos.getOffset() //NOI18N
                        + ", column=" + column + ", offset=" + offset //NOI18N
                        + ", doc.getLength=" + doc.getLength(), ex); //NOI18N
                }
            }
        }
    }
    t.addTaskListener(new Selector());

    return e;
}
 
源代码20 项目: netbeans   文件: CompletionTest.java
protected void exec(JEditorPane editor, TestStep step) throws Exception {
    try {
        BaseDocument doc = (BaseDocument) editor.getDocument();
        ref(step.toString());
        Caret caret = editor.getCaret();
        caret.setDot(step.getOffset() + 1);
        EditorOperator eo = new EditorOperator(testFileObj.getNameExt());
        eo.insert(step.getPrefix());
        if (!isJavaScript()) {
            caret.setDot(step.getCursorPos());
        }

        waitTypingFinished(doc);
        CompletionJListOperator comp = null;
        boolean print = false;
        int counter = 0;
        while (!print) {
            ++counter;
            if (counter > 5) {
                print = true;
            }
            try {
                comp = CompletionJListOperator.showCompletion();
            } catch (JemmyException e) {
                log("EE: The CC window did not appear");
                e.printStackTrace(getLog());
            }
            if (comp != null) {
                print = dumpCompletion(comp, step, editor, print) || print;
                waitTypingFinished(doc);
                CompletionJListOperator.hideAll();
                if (!print) {// wait for refresh
                    Thread.sleep(1000);
                    if (!isJavaScript()) {
                        caret.setDot(step.getCursorPos());
                    }
                }
            } else {
                long time = System.currentTimeMillis();
                String screenFile = time + "-screen.png";
                log("CompletionJList is null");
                log("step: " + step);
                log("captureScreen:" + screenFile);
                try {
                    PNGEncoder.captureScreen(getWorkDir().getAbsolutePath() + File.separator + screenFile);
                } catch (Exception e1) {
                    e1.printStackTrace(getLog());
                }
            }
        }
        waitTypingFinished(doc);
        int rowStart = Utilities.getRowStart(doc, step.getOffset() + 1);
        int rowEnd = Utilities.getRowEnd(doc, step.getOffset() + 1);
        String fullResult = doc.getText(new int[]{rowStart, rowEnd});
        String result = fullResult.trim();
        int removed_whitespaces = fullResult.length() - result.length();
        if (!result.equals(step.getResult().trim())) {
            ref("EE: unexpected CC result:\n< " + result + "\n> " + step.getResult());
        }
        ref("End cursor position = " + (caret.getDot() - removed_whitespaces));
    } finally {
        // undo all changes
        final UndoAction ua = SystemAction.get(UndoAction.class);
        assertNotNull("Cannot obtain UndoAction", ua);
        while (ua.isEnabled()) {
            runInAWT(new Runnable() {

                public void run() {
                    ua.performAction();
                }
            });
        }
    }
}