I am trying to restrict the input values inside JFormatdedTextField to [0.1, 100] using AbstractFormatter
public AbstractFormatter getFormatter(JFormattedTextField tf) {
NumberFormat f = DecimalFormat.getInstance();
f.setMinimumFractionDigits(1);
f.setMaximumFractionDigits(2);
InternationalFormatter iff= new InternationalFormatter(f);
iff.setAllowsInvalid(false);
iff.setMinimum(0.1);
iff.setMaximum(100.00);
return iff;
}
However, the abstract formatter has a strange behavior. Suppose that I would like to write the following number inside the interval: 0.2.
The abstract formatter blocks the first digit: 0. It is necessary to write 0.2 in 2 phases:
a] 1.2 //or any digit > 0
b] delete 1: 1.2->0.2
Such a behavior is for the user confusing. Is there any way to prevent this uncomfortable writing of numbers?
Thanks for your help.
I think that what you need is a JSPinner
:
JSpinner spin = new JSpinner(new SpinnerNumberModel(50 /*or whatever*/, 0.1, 100, 0.1));
or you can just remove the line
iff.setAllowsInvalid(false);
to remove the confusing behavior. The Javadocs for this method say:
Sets whether or not the value being edited is allowed to be invalid for a length of time (that is, stringToValue throws a ParseException). It is often convenient to allow the user to temporarily input an invalid value.
These will let the focus leave the component if the value is invalid and it will be reverted to the previous valid value. If you want to not allow losing focus use an input verifier as in said in the comments. There is an example in the Javadocs of JFormattedTextField
: http://docs.oracle.com/javase/8/docs/api/javax/swing/JFormattedTextField.html