I would like to change the behavior of a JSpinner so that when you click on the text, it selects it. This makes it easier to replace the field with the value that you want. Unfortunately, I can't get the behavior to work and instead, it just inserts the cursor in the text without selecting what is already there.
I have tried adding a focus Listener to both the JSpinner itself and the text area itself, via ((DefaultEditor) this.getEditor()).getTextField()
, yet neither of these seem to have the intended effect. My code (for the JSpinner itself) is as follows:
spinner.addFocusListener(new FocusAdapter(){
@Override
public void focusGained(FocusEvent e) {
((DefaultEditor) ((JSpinner) e.getSource()).getEditor()).getTextField().selectAll();
}
});
I'm not sure what the problem is. If it matters, I'm running Mac OS 10.7.5 and Java 6u43.
EDIT: I put a System.out.println
right at the beginning of the focusGained method and discovered that it was never called. So it looks like getting focus on the JSpinner isn't registering. Again, I tried putting the focusAdpater both on the spinner and on the text field (not at the same time though).
Much of the problem you are facing has to do with how the spinner validates any values within the spinner AFTER a focus event (and several other state events), which will circumvent the highlight.
The MacOS is even worse.
What I ended up doing was starting a
Thread
that waited a very short time period (around 25 milliseconds) and then usedSwingUtilities.invokeLater
to actually perform the selection...Updated with a example
Now, right about now, I'm praying for some really nice, simple, undocumented property that we can set that will mean we don't need to do all this :P
Don't know about a Mac but I've used this code on Windows:
I've also used this code for selecting text on a JFormattedTextField.