问题
This is a follow on SSCCE to my previous question:
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);
}
来源:https://stackoverflow.com/questions/20966239/how-to-notice-trap-when-user-types-invalid-value-when-jspinner-loses-focus