code_junkie

Is there an easy way to change the behavior of a Java/Swing control when it gets focus?

Nov 10th, 2011
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.24 KB | None | 0 0
  1. public class AutoClearingTextField extends JTextField {
  2. final FocusListener AUTO_CLEARING_LISTENER = new FocusListener(){
  3. @Override
  4. public void focusLost(FocusEvent e) {
  5. //onFocusLost(e);
  6. }
  7.  
  8. @Override
  9. public void focusGained(FocusEvent e) {
  10. selectAll();
  11. }
  12. };
  13.  
  14. public AutoClearingTextField(String string) {
  15. super(string);
  16. addListener();
  17. }
  18.  
  19. private void addListener() {
  20. addFocusListener(AUTO_CLEARING_LISTENER);
  21. }
  22. }
  23.  
  24. public class SelectAllListener implements FocusListener {
  25. private static INSTANCE = new SelectAllListener();
  26.  
  27. public void focusLost(FocusEvent e) { }
  28.  
  29. public void focusGained(FocusEvent e) {
  30. if (e.getSource() instanceof JTextComponent) {
  31. ((JTextComponent)e.getSource()).selectAll();
  32. }
  33. };
  34.  
  35. public static void addSelectAllListener(JTextComponent tc) {
  36. tc.addFocusListener(INSTANCE);
  37. }
  38.  
  39. public static void removeSelectAllListener(JTextComponent tc) {
  40. tc.removeFocusListener(INSTANCE);
  41. }
  42. }
  43.  
  44. public static void addSelectAllListener(JSpinner spin) {
  45. if (spin.getEditor() instanceof JTextComponent) {
  46. addSelectAllListener((JTextComponent)spin.getEditor());
  47. }
  48. }
  49.  
  50. public static void addSelectAllListener(JComboBox combo) {
  51. JComponent editor = combo.getEditor().getEditorComponent();
  52. if (editor instanceof JTextComponent) {
  53. addSelectAllListener((JTextComponent)editor);
  54. }
  55. }
  56.  
  57. void addTextFocusSelect(JComponent component){
  58. if(component instanceof JTextComponent){
  59. component.addFocusListener(new FocusAdapter() {
  60. @Override
  61. public void focusGained(FocusEvent event) {
  62. super.focusGained(event);
  63. JTextComponent component = (JTextComponent)event.getComponent();
  64. // a trick I found on JavaRanch.com
  65. // Without this, some components don't honor selectAll
  66. component.setText(component.getText());
  67. component.selectAll();
  68. }
  69. });
  70.  
  71. }
  72. else
  73. {
  74. for(Component child: component.getComponents()){
  75. if(child instanceof JComponent){
  76. addTextFocusSelect((JComponent) child);
  77. }
  78. }
  79. }
  80. }
Add Comment
Please, Sign In to add comment