This is a follow on SSCCE to my previous question:
This JSpinner background goes RED when users types an invalid value and WHITE when valid. However, if value is invalid and user clicks away from this field the value reverts to whatever was previous.
I want to notice/trap when this happens and inform the user that his typed value is NOT being used, and disable any other functions that rely on this value.
How can I ammend the following code to accomplish that?
public static void main(String[] args) {
// TODO Auto-generated method stub
JFrame F = new JFrame();
F.setVisible(true);
JPanel p = new JPanel();
final JSpinner spin2 = new JSpinner();
spin2.setModel(new SpinnerNumberModel(10, 10, 100, 1));
JComponent comp = spin2.getEditor();
JFormattedTextField field = (JFormattedTextField) comp.getComponent(0);
DefaultFormatter formatter = (DefaultFormatter) field.getFormatter();
formatter.setCommitsOnValidEdit(true);
((JSpinner.DefaultEditor)Position.getEditor()).getTextField().addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
//LOG.info("" + evt);
if ("editValid".equals(evt.getPropertyName())) {
if (Boolean.FALSE.equals(evt.getNewValue())) {
SpinnerNumberModel model = (SpinnerNumberModel) Position.getModel();
((JSpinner.DefaultEditor)Position.getEditor()).getTextField().setBackground(Color.RED);
((JSpinner.DefaultEditor)Position.getEditor()).getTextField().setToolTipText("Amount must be in range [ " + model.getMinimum() + " ... " + model.getMaximum() + " ] for this symbol");
}
else{
((JSpinner.DefaultEditor)Position.getEditor()).getTextField().setBackground(Color.WHITE);
}
}
}
});
p.add(spin2);
F.add(p);
F.pack();
F.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
If you need the user's input to persist even if he/she enters wrong input then set the focus lost behaviour to
PERSIST
.If you need to notify the user for invalid values typed then add a
KeyListener
to the spinner's text field. ThatKeyListener
will callcommitEdit()
which in turn will fail if the user's input is invalid, throwing a checked exception that you will catch and notify the user back.If you need to notify the user for invalid values when the focus is lost then add a
FocusListener
to the spinner's text field. ThatFocusListener
will callcommitEdit()
which in turn will fail if the user's input is invalid, throwing a checked exception that you will catch and notify the user back.Putting them all together: