sehlstrom
sehlstrom

Reputation: 389

Make JFormattedTextField accept decimal with more than 3 digits

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?

Upvotes: 3

Views: 5908

Answers (1)

mKorbel
mKorbel

Reputation: 109823

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;
        }
    });
}

Upvotes: 8

Related Questions