I want to implement autoselect when a user tabs through the JTextFields and JSpinners in my forms. For this I am using this Listener:
public class AutoSelect implements FocusListener {
@Override
public void focusGained(final FocusEvent e) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
if (e.getSource() instanceof JTextField) {
try {
JTextField t = (JTextField) e.getComponent();
t.selectAll();
} catch (ClassCastException ex) {
//
}
}else if (e.getSource() instanceof JSpinner){
JSpinner spinner = (JSpinner)e.getComponent();
JTextField tf = ((JSpinner.DefaultEditor)spinner.getEditor()).getTextField();
tf.selectAll();
}
}
});
}
@Override
public void focusLost(FocusEvent e) {
//
}
}
Only it doesn´t work for my spinners. The event is beeing fired, the correct lines are executed, only nothing happens. I suspect I am not using the .getTextField() correctly. Does anyone have a working solution for this ?
tf.selectAll();should be wrapped intoinvokeLater, everything withFocusis pretty asynchronous (more in Oracle tutorialHow to use Focus, FocusSubsystem),then
invokeLater(not true in all cases for allJComponents, but by default) forJTextComponentsmove this event to the end of queue, works for me quite correctly