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();
try {
  JMIUtils utils = JMIUtils.get(baseDoc);
  Resource resource = utils.getResource();
  Element el = resource.getElementByOffset(offset);
} finally {

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

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