Odd behavior of SpinnerNumberModel in Java

I am trying to configure JSpinner using SpinnerNumberModel with value = 0.0005, min = 0.0, max = 1.0 and step size = 0.0005. However, when I create a counter with these parameters, I observe a very strange behavior. Instead of starting at 0.0005 and increasing by 0.0005 with each click of the up arrow, the value seems to stick to 0.

To make sure that this is not just a formatting issue, I printed the counter value after each change event. Of course, for each click of the up arrow, the console displays the value as 0, and then 0.0005, regardless of how many times the counter has clicked.

Below is the code I used to verify this, including a counter with slightly different values, which is great for comparison.

import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;

public class Main {

    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setSize(200, 80);
        JPanel panel = new JPanel();
        panel.setLayout(new BorderLayout());
        final JSpinner spinner1 = new JSpinner(new SpinnerNumberModel(0.0005, 0.0, 1.0, 0.0005));
        final JSpinner spinner2 = new JSpinner(new SpinnerNumberModel(0.05, 0.0, 1.0, 0.05));
        panel.add(spinner1, BorderLayout.NORTH);
        panel.add(spinner2, BorderLayout.SOUTH);
        frame.add(panel);
        spinner1.addChangeListener(new ChangeListener() {
            public void stateChanged(ChangeEvent e) {
                System.out.println("spinner1: " + ((Number) spinner1.getValue()).doubleValue());
            }
        });
        spinner2.addChangeListener(new ChangeListener() {
            public void stateChanged(ChangeEvent e) {
                System.out.println("spinner2: " + ((Number) spinner2.getValue()).doubleValue());
            }
        });
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

}

- , spinner2 , spinner1 ?

.

Edit: Peter , spinner . , : spinner1.setEditor(new JSpinner.NumberEditor(spinner1, "0.0000"));.

+5
1

, JFormattedTextField . :

public void commitEdit() throws ParseException {
    AbstractFormatter format = getFormatter();

    if (format != null) {
        setValue(format.stringToValue(getText()), false, true);
    }
}

0,0005 0.0, 0.0 , 0,0005, , TextField 0,0

spinner.

final JSpinner spinner1 = new JSpinner(new SpinnerNumberModel(0.0005, 0.0, 1.0, 0.0005)) {
      @Override
      protected JComponent createEditor( SpinnerModel model )
      {
        return new NumberEditor(this, "0.0000");//needed decimal format
      }
    };
+9

All Articles