How do I make it such that my text fields auto select their content when they get the input focus?

John Zukowski

You can either attach a FocusListener to every text field you wish to perform the auto-select or replace the FocusManager. By replacing the focus manager, you can have it check what type of component gets the input focus and act accordingly. However, by completely replacing the focus manager, you lose any special behavior the current one has.

The following example code demonstrates the behavior. You can change the instanceof check to be JTextComponent instead of JTextField if you wish for all text components to act this way.

import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;
public class AutoSelectFocusManager extends DefaultFocusManager {
  // To enable - FocusManager.setCurrentManager(new AutoSelectFocusManager());
  public void focusNextComponent(Component originalComp) {
    super.focusNextComponent(originalComp);
    Component newComp = SwingUtilities.windowForComponent(originalComp).getFocusOwner();
    if ((newComp != null) && (newComp instanceof JTextField)) {
      ((JTextField)newComp).selectAll();
    }
  }
  public void focusPreviousComponent(Component originalComp) {
    super.focusPreviousComponent(originalComp);
    Component newComp = SwingUtilities.windowForComponent(originalComp).getFocusOwner();
    if ((newComp != null) && (newComp instanceof JTextField)) {
      ((JTextField)newComp).selectAll();
    }           
  }
  public static void main (String args[]) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(3);
    FocusManager.setCurrentManager(new AutoSelectFocusManager());
    Container content = frame.getContentPane();
    JTextField tf1 = new JTextField("Hello");
    JTextField tf2 = new JTextField("Hello");
    JTextField tf3 = new JTextField("Hello");
    content.add(tf1, BorderLayout.NORTH);
    content.add(tf2, BorderLayout.CENTER);
    content.add(tf3, BorderLayout.SOUTH);
    frame.pack();
    frame.show();
  }
}
0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact