简体   繁体   中英

Make input of JSpinner matching the NumberEditor

If I set a number editor in a JSpinner (for example '# Hz') the input must always correspond to this format.

Ie 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?

So if this is my Spinner: 我的带数字编辑器的微调器

And I enter just a Number without the 'Hz': 输入一个“空白”号码

So spinner doesnt accept the 450 and falls back to 440 Hz: 微调器不接受输入的数字

So I have to enter the number with a valid unit: 我真的必须添加单位

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


}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM