我想使JavaFX微调器成为小数点后3位的双精度值,所以我就这样制作了Spinner
:
Spinner<Double> spinner = new Spinner<Double>();
SpinnerValueFactory<Double> valueFactory =
new SpinnerValueFactory.DoubleSpinnerValueFactory(0, 512, 51.197, 1);
spinner.setValueFactory(valueFactory);
spinner.setEditable(true);
我刚使微调器的初始值为51.197,但是当我运行此代码时,初始值为51.2;当我将微调框编辑为52.666时,无法使用此值。我认为小数位有问题。
我想将值形式用作###.###
。如何处理JavaFX Spinner
小数位?
答案 0 :(得分:2)
我用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);