输入与 NumberEditor 匹配的 JSpinner

Make input of JSpinner matching the NumberEditor

如果我在 JSpinner 中设置数字编辑器(例如“# Hz”),输入必须始终符合此格式。

即输入“0”被拒绝,仅接受“0 Hz”。

有没有简单的方法让输入的空白​​数字被接受并自动调整格式?

如果这是我的 Spinner:

我只输入了一个没有 'Hz' 的数字:

所以微调器不接受 450 并回落到 440 Hz:

所以我必须输入有效单位的数字:

好的,我找到了解决这个问题的方法。

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());
            }
        }
    });


}

}