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 javax.swing.JComponent; import java.awt.Component; import java.awt.Container; public class Main { /** * Obtains selected text * * @param component the component that is an EditorPane or some of its * subcomponents is an EditorPane * @return current caret position */ public static String getSelectedText(Container component) { if (component.getClass().getName().indexOf("EditorPane") >= 0) { try { java.lang.reflect.Method caretGetter = component.getClass().getMethod("getSelectedText", new Class[] {}); Object result = caretGetter.invoke(component, new Object[] {}); if (result == null) { return null; } return (String) result; } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("Method invocation exception caught"); } } for (int i = 0; i < component.getComponentCount(); i++) { Component childComponent = component.getComponent(i); if (childComponent instanceof JComponent) { return getSelectedText((JComponent) childComponent); } } return null; } }