/src/elements/TextSelector.java

http://inequity.googlecode.com/ · Java · 58 lines · 36 code · 10 blank · 12 comment · 8 complexity · 77d9852181e81c415992807c5cb96430 MD5 · raw file

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