If I set a number editor in a JSpinner (for example '# Hz') the input must always correspond to this format.
I.e. the input of '0' is rejected and only '0 Hz' is accepted.
Is there an easy way to let the input of blank numbers be accepted and automatically adjusted to the format?
And I enter just a Number without the 'Hz':
Ok, I found a way to solve this problem.
public class ExtendedJSpinner extends JSpinner {
public ExtendedJSpinner(){
}
public ExtendedJSpinner(SpinnerModel model){
super(model);
}
@Override
public void setEditor(JComponent editor){
super.setEditor(editor);
JFormattedTextField textField = (JFormattedTextField) editor.getComponent(0);
final JSpinner obj = this;
// Listen for changes in the text
textField.getDocument().addDocumentListener(new DocumentListener() {
public void changedUpdate(DocumentEvent e) {}
public void removeUpdate(DocumentEvent e) {}
public void insertUpdate(DocumentEvent e) {
String text = textField.getText();
try {
float number = Float.valueOf(text).floatValue();
obj.setValue(number);
}
catch(Exception ex) {
System.out.println("insert failed: " + textField.getText());
}
}
});
}
}