0

How to create a JFormattedTextField which can accept any number of fractional digits in a decimal number?

 JFormattedTextField tf = new JFormattedTextField();
      tf
      .setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(
          new javax.swing.text.NumberFormatter(new java.text.DecimalFormat())));

This accepts only 3 fractional digits since maximum fraction digits is 3 by default for DecimalFormat.

MMPgm
  • 109
  • 1
  • 1
  • 6
  • https://docs.oracle.com/javase/7/docs/api/java/text/DecimalFormat.html#setMaximumFractionDigits%28int%29 – koem Jan 22 '16 at 05:53
  • may be this will help:http://stackoverflow.com/questions/14876695/make-jformattedtextfield-accept-decimal-with-more-than-3-digits – soorapadman Jan 22 '16 at 05:55
  • It asks to set maximum fraction digits. But in my case i dont know the maximum fraction digits – MMPgm Jan 22 '16 at 06:12

1 Answers1

0

This will set the number of fractional digits to a maximum:

JFormattedTextField tf = new JFormattedTextField();
DecimalFormat df = new java.text.DecimalFormat();
df.setMaximumFractionDigits(Integer.MAX_VALUE);
tf.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(
    new javax.swing.text.NumberFormatter(df)));

Please note that this does not mean "any number" as in your question. As specified in Javadoc of setMaximumFractionDigits:

The concrete subclass may enforce an upper limit to this value appropriate to the numeric type being formatted.

this doesn't matter in your example, but

For formatting numbers other than BigInteger and BigDecimal objects, the lower of newValue and 340 is used. Negative input values are replaced with 0.

But I guess this should be enough for most cases.

Würgspaß
  • 4,660
  • 2
  • 25
  • 41