Make JFormattedTextField accept decimal with more than 3 digits

梦想与她 提交于 2019-12-20 02:50:59

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!