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

Apache NetBeans Wiki Index

Note: These pages are being reviewed.

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/column of the currently selected editor?

        JTextComponent editor = org.netbeans.api.editor.EditorRegistry.lastFocusedComponent();

        //using StyledDocument
            StyledDocument sdocument = (StyledDocument) editor.getDocument();

            int line = NbDocument.findLineNumber(sdocument, editor.getCaretPosition());
            int column = NbDocument.findLineColumn(sdocument, editor.getCaretPosition());
        //using BaseDocument
            try {
                BaseDocument bdocument = Utilities.getDocument(editor);
                int line = Utilities.getLineOffset(bdocument, editor.getCaretPosition());
            } catch (BadLocationException ex) {

Applies to: NetBeans 4.0 and newer