Trying to implement it so that the text in my JSpinner / JTextField's are selected when it gains focus I implemented this class (modified version of one I found in this forum):
public class CommonUtilityMethods {
private static FocusAdapter allTextSelector;
// Ensures that all the text in a JTextComponent will be
// selected whenever the cursor is in that field (gains focus):
public static void setSelectAllFieldText(JComponent comp) {
if (allTextSelector == null) {
// Lazy initialization of one adapter for all components:
allTextSelector = new java.awt.event.FocusAdapter() {
public void focusGained(FocusEvent ev) {
if(ev.getSource() instanceof JTextComponent) {
JTextComponent textComp = (JTextComponent) ev.getSource();
textComp.selectAll();
} else if(ev.getSource() instanceof valueSpinner) {
valueSpinner vcomp = (valueSpinner)ev.getSource();
((JSpinner.DefaultEditor )vcomp.getEditor ()).getTextField().selectAll();
}
}
};
}
comp.addFocusListener(allTextSelector);
}
}
And then I add the listener using the setSelectAllFieldText method.
It does however not work as expected. On JTextField's a selection is only made the first time the textfield gains focus (so I get it to select all text if I remove the focus from the JInternalFrame which it is located in and then give it focus again).
On JSpinner no selection is made at all..