I've added a FocusAdapter
to my JFormattedTextField
to select its contents when focus is lost, so that the text is selected when tabbed back into but not clicked into.
final FocusAdapter listener = new FocusAdapter()
{
@Override
public void focusLost(FocusEvent e)
{
super.focusLost(e);
AccessibleEditableText text = e.getComponent().getAccessibleContext().getAccessibleEditableText();
text.selectText(0, text.toString().length());
}
};
yearPublishedTextField.addFocusListener(listener);
However, this doesn't work for this particular text field since I added the following formatter:
NumberFormat nf = NumberFormat.getIntegerInstance();
nf.setGroupingUsed(false);
yearPublishedTextField.setFormatterFactory(new DefaultFormatterFactory(new NumberFormatter(nf)));
I've noticed that, on reacquiring focus, the caret gets set to the zero position. Can anyone explain why the formatter is doing this, and suggest a way to work around this issue?