3

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?

sehlstrom
  • 389
  • 2
  • 7
  • 18
  • 1
    This is not an answer, but alternative http://stackoverflow.com/a/8017847/597657 – Eng.Fouad Feb 14 '13 at 14:14
  • 1
    Seems like a job for `DocumentFilter` see [here](http://stackoverflow.com/questions/14305921/detecting-jtextfield-deselect-event/14305952#14305952) for an example of `DocumentFilter` and other ways and their respective examples. You can have variable lengthed mask but thats too much IMO but incase you want to see it [here](https://forums.oracle.com/forums/thread.jspa?threadID=1363095). – David Kroukamp Feb 14 '13 at 14:15

1 Answers1

8

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;
        }
    });
}
mKorbel
  • 109,525
  • 20
  • 134
  • 319