Search code examples
javaswingjspinner

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.

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?

So if this is my Spinner: my Spinner with number editor

And I enter just a Number without the 'Hz': enter a 'blank' number

So spinner doesnt accept the 450 and falls back to 440 Hz: spinner doesnt accept the entered number

So I have to enter the number with a valid unit: I really have to add the unit


Solution

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

    }