DevFaqJavaModelCaretModelElement

How do I get the element under the caret?

Note: This FAQ item applies only to NetBeans 4.x and 5.x. The Java parsing infrastructure in NetBeans 6 has been replaced with a new API.

Null checks, class match checks and exception handling omitted:

JTextComponent ed = Registry.getMostActiveComponent();
BaseDocument baseDoc = (BaseDocument) ed.getDocument();
int offset = ed.getCaret().getDot();
JavaModel.getJavaRepository().beginTrans(false);
try {
  JMIUtils utils = JMIUtils.get(baseDoc);
  Resource resource = utils.getResource();
  JavaModel.setClassPath(resource);
  Element el = resource.getElementByOffset(offset);
} finally {
  JavaModel.getJavaRepository().endTrans();
}

To find the method the caret is in (if any), use:

JavaModelUtil.getDeclaringFeature(el);
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