-
Notifications
You must be signed in to change notification settings - Fork 1
DevFaqFindCaretPositionInEditor
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
}
}
}
Or
org.netbeans.api.editor.EditorRegistry.lastFocusedComponent().getCaretPosition()
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) {
Exceptions.printStackTrace(ex);
}
}
Applies to: NetBeans 4.0 and newer
The content in this page was kindly donated by Oracle Corp. to the Apache Software Foundation.
This page was exported from http://wiki.netbeans.org/DevFaqFindCaretPositionInEditor , that was last modified by NetBeans user Markiewb on 2016-03-05T13:25:27Z.
NOTE: This document was automatically converted to the AsciiDoc format on 2018-01-26, and needs to be reviewed.
Apache NetBeans is an effort undergoing incubation at The Apache Software Foundation (ASF).
Incubation is required of all newly accepted projects until a further review indicates that the infrastructure, communications, and decision making process have stabilized in a manner consistent with other successful ASF projects.
While incubation status is not necessarily a reflection of the completeness or stability of the code, it does indicate that the project has yet to be fully endorsed by the ASF.
This wiki is an experiment pending Apache NetBeans Community approval.