Skip to Main Content

Java SE (Java Platform, Standard Edition)

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

select all on focus gained (JFormattedTextField)

843804Dec 24 2004 — edited Dec 27 2004
I'd like to "select all" when a formatted text field gains focus. I've added a listener to do this, but it does not work. Any ideas why? The below code works if I change from JFormattedTextField to JTextField.
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.GridLayout;
import java.text.NumberFormat;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class TestSelectAllOnFocus {
  
  public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
    JPanel content = new JPanel(new GridLayout(5, 0));
    
    NumberFormat numberFormat = NumberFormat.getIntegerInstance();
    numberFormat.setGroupingUsed(false);
    
    for (int i = 0; i < 5; i++) {
      JTextField field = new JFormattedTextField(numberFormat);
      field.setColumns(5);
      field.setText("1000" + (i + 1));
      
      field.addFocusListener(new FocusListener() {
        public void focusGained(FocusEvent e) {
          JTextField field = (JTextField) e.getSource();
          System.err.println("select all for field with text: " +
            field.getText());
          field.selectAll();
        }
        public void focusLost(FocusEvent e) {
        }
      });
      content.add(field);
    }
    
    frame.setContentPane(content);
    frame.pack();
    frame.setVisible(true);
  }
  
}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jan 24 2005
Added on Dec 24 2004
2 comments
386 views