问题
I have a JFormattedTextField
that should be able to accept double numbers with more than 3 decimal digits. It accepts entries 0.1
, 0.01
, 0.001
but rejects 0.0001
and numbers with more decimal digits.
This is how my code works now:
DecimalFormat decimalFormat = new DecimalFormat("0.0E0");
JFormattedTextField txtfield = new JFormattedTextField(decimalFormat.getNumberInstance(Locale.getDefault()));
How do I get my text field to accept numbers with more than 3 decimal digits?
回答1:
It accepts entries 0.1, 0.01, 0.001 but rejects 0.0001 and numbers with more decimal digits.
this should be settable in NumberFormat / DecimalFormat (in your case) by setMinimumFractionDigits(int)
, setMaximumFractionDigits(int)
and /or with setRoundingMode(RoundingMode.Xxx)
, more in Oracle tutorial about Formatting
for example
final JFormattedTextField textField1 = new JFormattedTextField(new Float(10.01));
textField1.setFormatterFactory(new AbstractFormatterFactory() {
@Override
public AbstractFormatter getFormatter(JFormattedTextField tf) {
NumberFormat format = DecimalFormat.getInstance();
format.setMinimumFractionDigits(2);
format.setMaximumFractionDigits(2);
format.setRoundingMode(RoundingMode.HALF_UP);
InternationalFormatter formatter = new InternationalFormatter(format);
formatter.setAllowsInvalid(false);
formatter.setMinimum(0.0);
formatter.setMaximum(1000.00);
return formatter;
}
});
}
来源:https://stackoverflow.com/questions/14876695/make-jformattedtextfield-accept-decimal-with-more-than-3-digits