I'd like to create JSpinners with support for non-integer values such as 2.01 and -3.456, so getValue() returns a Double.
Not only this, but I'd like the step size should be dynamic using something like following formula (10% of the magnitude):
stepSize = 0.1 * pow(10, round( log(currentValue) ));
Is it possible? Or should I ask, is it worth the hassle?
Update:
With adaption of Vishal's answer, I've produced the following class to make nice double spinners. So far, they've shown to work really well in my program although I will abstract the adaptive step size into another, parent class so I can make AdaptiveDoubleSpinners and AdaptiveIntegerSpinners later.
import javax.swing.JSpinner;
import javax.swing.SpinnerNumberModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class DoubleSpinner extends JSpinner {
private static final long serialVersionUID = 1L;
private static final double STEP_RATIO = 0.1;
private SpinnerNumberModel model;
public DoubleSpinner() {
super();
// Model setup
model = new SpinnerNumberModel(0.0, -1000.0, 1000.0, 0.1);
this.setModel(model);
// Step recalculation
this.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
Double value = getDouble();
// Steps are sensitive to the current magnitude of the value
long magnitude = Math.round(Math.log10(value));
double stepSize = STEP_RATIO * Math.pow(10, magnitude);
model.setStepSize(stepSize);
}
});
}
/**
* Returns the current value as a Double
*/
public Double getDouble() {
return (Double)getValue();
}
}