/src/elements/TextSelector.java
http://inequity.googlecode.com/ · Java · 58 lines · 36 code · 10 blank · 12 comment · 8 complexity · 77d9852181e81c415992807c5cb96430 MD5 · raw file
- package elements;
- import java.awt.KeyboardFocusManager;
- import java.beans.PropertyChangeEvent;
- import java.beans.PropertyChangeListener;
- import javax.swing.text.JTextComponent;
- /**
- *
- * @author Tomaz Strazisnik
- * http://www.javalobby.org/java/forums/t17439.html
- */
- public class TextSelector
- {
- private static FocusHandler installedInstance;
- /**
- * Install an PropertyChangeList listener to the default focus manager
- * and selects text when a text component is focused.
- */
- public static void install()
- {
- //already installed
- if (installedInstance != null)
- return;
- installedInstance = new FocusHandler();
- KeyboardFocusManager kfm = KeyboardFocusManager.getCurrentKeyboardFocusManager();
- kfm.addPropertyChangeListener("focusOwner", (PropertyChangeListener) installedInstance);
- }
- public static void uninstall()
- {
- if (installedInstance != null)
- {
- KeyboardFocusManager kfm = KeyboardFocusManager.getCurrentKeyboardFocusManager();
- kfm.removePropertyChangeListener("focusOwner", installedInstance);
- }
- }
- private static class FocusHandler implements PropertyChangeListener {
- public void propertyChange(PropertyChangeEvent evt)
- {
- if (evt.getNewValue() instanceof JTextComponent)
- {
- JTextComponent text = (JTextComponent) evt.getNewValue();
- //select text if the component is editable
- //and the caret is at the end of the text
- if (text.isEditable() && text.getDocument().getLength() == text.getCaretPosition())
- text.selectAll();
- }
- }
- }
- }