PageRenderTime 17ms CodeModel.GetById 12ms app.highlight 2ms RepoModel.GetById 2ms app.codeStats 0ms

/src/elements/TextSelector.java

http://inequity.googlecode.com/
Java | 58 lines | 36 code | 10 blank | 12 comment | 8 complexity | 77d9852181e81c415992807c5cb96430 MD5 | raw file
 1package elements;
 2
 3import java.awt.KeyboardFocusManager;
 4import java.beans.PropertyChangeEvent;
 5import java.beans.PropertyChangeListener;
 6import javax.swing.text.JTextComponent;
 7
 8/**
 9 *
10 * @author Tomaz Strazisnik
11 * http://www.javalobby.org/java/forums/t17439.html
12 */
13public class TextSelector
14{
15  private static FocusHandler installedInstance;
16
17  /**
18   * Install an PropertyChangeList listener to the default focus manager
19   * and selects text when a text component is focused.
20   */
21  public static void install()
22  {
23    //already installed
24    if (installedInstance != null)
25      return;
26
27    installedInstance = new FocusHandler();
28
29    KeyboardFocusManager kfm = KeyboardFocusManager.getCurrentKeyboardFocusManager();
30
31    kfm.addPropertyChangeListener("focusOwner", (PropertyChangeListener) installedInstance);
32  }
33
34  public static void uninstall()
35  {
36    if (installedInstance != null)
37    {
38      KeyboardFocusManager kfm = KeyboardFocusManager.getCurrentKeyboardFocusManager();
39      kfm.removePropertyChangeListener("focusOwner", installedInstance);
40    }
41  }
42
43  private static class FocusHandler implements PropertyChangeListener {
44
45    public void propertyChange(PropertyChangeEvent evt)
46    {
47      if (evt.getNewValue() instanceof JTextComponent)
48      {
49          JTextComponent text = (JTextComponent) evt.getNewValue();
50          //select text if the component is editable
51          //and the caret is at the end of the text
52          if (text.isEditable() && text.getDocument().getLength() == text.getCaretPosition())
53              text.selectAll();
54      }
55    }
56  }
57}
58