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.
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(); } }); } });
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(); } }); } } });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With