Java tutorial
//package com.java2s; /* * Copyright 2001-2008 Aqris Software AS. All rights reserved. * * This program is dual-licensed under both the Common Development * and Distribution License ("CDDL") and the GNU General Public * License ("GPL"). You may elect to use one or the other of these * licenses. */ import java.awt.Container; public class Main { /** * Gets the current cursor position in the component or one of it's * subcomponents. * * @param component the component that is an EditorPane or some of its * subcomponents is an EditorPane * @return current caret position */ public static int getCaretPosition(Container component) { if (component.getClass().getName().indexOf("EditorPane") >= 0) { try { java.lang.reflect.Method caretGetter = component.getClass().getMethod("getCaretPosition", new Class[] {}); Object result = caretGetter.invoke(component, new Object[] {}); return ((Integer) result).intValue(); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("Method invocation exception caught"); } } for (int i = 0; i < component.getComponentCount(); i++) { java.awt.Component childComponent = component.getComponent(i); if (childComponent instanceof javax.swing.JComponent) { int result = getCaretPosition((javax.swing.JComponent) childComponent); if (result >= 0) { return result; } } } return -1; } }