Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select all text in a JFormattedTextField when it gets focus?

I have a small Java desktop app that uses Swing. There is a data entry dialog with some input fields of different types (JTextField, JComboBox, JSpinner, JFormattedTextField). When I activate the JFormattedTextFields either by tabbing through the form or by clicking it with the mouse, I would like it to select all the text that it currently contains. That way, users could just start typing and overwrite the default values.

How can I do that? I did use a FocusListener/FocusAdapter that calls selectAll() on the JFormattedTextField, but it doesn't select anything, although the FocusAdapter's focusGained() method is called (see code sample below).

private javax.swing.JFormattedTextField pricePerLiter; // ... pricePerLiter.setFormatterFactory(     new JFormattedTextField.AbstractFormatterFactory() {     private NumberFormatter formatter = null;     public JFormattedTextField.AbstractFormatter          getFormatter(JFormattedTextField jft) {         if (formatter == null) {             formatter = new NumberFormatter(new DecimalFormat("#0.000"));             formatter.setValueClass(Double.class);         }         return formatter;     } }); // ... pricePerLiter.addFocusListener(new java.awt.event.FocusAdapter() {     public void focusGained(java.awt.event.FocusEvent evt) {         pricePerLiter.selectAll();     } }); 

Any ideas? The funny thing is that selecting all of its text apparently is the default behavior for both JTextField and JSpinner, at least when tabbing through the form.

like image 398
Robert Petermeier Avatar asked Jul 24 '09 15:07

Robert Petermeier


2 Answers

Wrap your call with SwingUtilities.invokeLater so it will happen after all pending AWT events have been processed :

pricePerLiter.addFocusListener(new java.awt.event.FocusAdapter() {     public void focusGained(java.awt.event.FocusEvent evt) {         SwingUtilities.invokeLater(new Runnable() {             @Override             public void run() {                 pricePerLiter.selectAll();             }         });     } }); 
like image 129
Eugene Ryzhikov Avatar answered Oct 12 '22 23:10

Eugene Ryzhikov


In addition to the above, if you want this for all text fields you can just do:

KeyboardFocusManager.getCurrentKeyboardFocusManager()     .addPropertyChangeListener("permanentFocusOwner", new PropertyChangeListener() {     public void propertyChange(final PropertyChangeEvent e)     {         if (e.getNewValue() instanceof JTextField)         {             SwingUtilities.invokeLater(new Runnable()             {                 public void run()                 {                     JTextField textField = (JTextField)e.getNewValue();                     textField.selectAll();                 }             });          }     } }); 
like image 35
camickr Avatar answered Oct 12 '22 23:10

camickr