DevFaqFindCaretPositionInEditor

Revision as of 23:04, 11 September 2015 by Markiewb (Talk | contribs)

How can I get the position of the caret in the currently selected editor window?

You need to first get the selected node (which if the Editor is selected, should correspond to the file being edited); get the most recent editor pane open on it; and then access the caret:

Node[] n = TopComponent.getRegistry().getActivatedNodes();
if (n.length == 1) {
    EditorCookie ec = (EditorCookie) n[0].getCookie(EditorCookie.class);
    if (ec != null) {
        JEditorPane[] panes = ec.getOpenedPanes();
        if (panes.length > 0) {
            int cursor = panes[0].getCaret().getDot();
            String selection = panes[0].getSelectedText();
            // USE selection
        }
    }
}


How can I get the linenumber of the currently selected editor?

                    try {
                        JTextComponent editor = org.netbeans.api.editor.EditorRegistry.lastFocusedComponent();
                        BaseDocument document = org.netbeans.editor.Utilities.getDocument(editor);

                        int lineEnd = org.netbeans.editor.Utilities.getLineOffset(document, ed.getSelectionEnd());
                        int lineStart = org.netbeans.editor.Utilities.getLineOffset(document, ed.getSelectionStart());
                        if (lineEnd == lineStart) {
                            //single line 
                            System.out.println("currentLine = " + lineStart);
                        } else {
                            //multiple lines

                        }
                    } catch (BadLocationException ex) {
                        Exceptions.printStackTrace(ex);
                    }

Applies to: NetBeans 4.0 and newer

Not logged in. Log in, Register

By use of this website, you agree to the NetBeans Policies and Terms of Use. © 2012, Oracle Corporation and/or its affiliates. Sponsored by Oracle logo