Search code examples
javafxspinner

How can I set decimal places in JavaFX spinner?


I want to make JavaFX spinner with 3 decimal places as a double value, so I just made Spinner like this:

Spinner<Double> spinner = new Spinner<Double>();
SpinnerValueFactory<Double> valueFactory =
    new SpinnerValueFactory.DoubleSpinnerValueFactory(0, 512, 51.197, 1);
spinner.setValueFactory(valueFactory);
spinner.setEditable(true);

I just made spinner with initial value as 51.197, but when I run this code, initial value is 51.2; and when I edit spinner as 52.666, I can't use this value. I think that the decimal place is problem. I want to use value form as ###.###. How can I handle JavaFX Spinner decimal place?


Solution

  • I solved this problem with StringConverter.

    StringConverter<Double> doubleConverter = new StringConverter<Double>() {
    private final DecimalFormat df = new DecimalFormat("###.###");
    @Override
    public String toString(Double object) {
        if (object == null) {return "";}
        return df.format(object);}
    @Override
    public Double fromString(String string) {
        try {
            if (string == null) {return null;}
            string = string.trim();
            if (string.length() < 1) {return null;}     
            return df.parse(string).doubleValue();
        } catch (ParseException ex) {throw new RuntimeException(ex);}
        }
    };
    
    Spinner<Double> spinner = new Spinner<Double>();
    SpinnerValueFactory<Double> valueFactory = new SpinnerValueFactory.DoubleSpinnerValueFactory(0, 512, 51.197, 1);
    spinner.setValueFactory(valueFactory);
    spinner.setEditable(true);
    
    SpinnerValueFactory.setConverter(doubleConverter);