How to set jFormattedTextField so it only allows 2 numbers?
Asked Answered
C

1

5

I'm a beginner in Java, and NetBeans. I'm trying to make a simple program where you introduce 2 numbers and their sum gets divided by two. However, I'm using JFormattedTExtFields and I don't know how to customize the allowed input in them. Basically I'm trying to find out how to:

  • Only allow numbers to be entered in JFormmatedTextField;
  • Only allow a certain amount of numbers;
Charmeuse answered 26/12, 2011 at 17:23 Comment(1)
may be you have look at JSpinner too,Condensed
D
9

You could use a NumberFormat and specify the maximum number of integer digits with setMaximumIntegerDigits.

Here's a nice article.

Basically you can do something like:

NumberFormat f = NumberFormat.getNumberInstance(); 
f.setMaximumIntegerDigits(maxDigitsAmount);
JFormattedTextField field = new JFormattedTextField(f);

The Format should guarantee that the inserted String satisfy the format. Anyway even if a number is supplied, the textfield will store it as a String. So if you need your original Integer you need to rebuild it like suggested @noise:

Integer i = Integer.toString(field.getText());
Decaffeinate answered 26/12, 2011 at 17:27 Comment(3)
Thanks! Oh and another thing. If anyone can tell me how to set the text of a textfield to an int? Example, I have 2 ints(The values entered in the 2 text boxes) and a rezult int, which is equal to the sum of the 2 ints. If I call the jTextField1.setText(rezult) it asks for string instead of int. Any help?Charmeuse
Thanks alot guys. I've almost fixed it, except when I call JFormattedTextField field = new JFormattedTextField(f); it gives me an error "Cannot find symbol JFormattedTextField". Any idea?Charmeuse
you should include javax.swing.JFormattedTextFieldDecaffeinate

© 2022 - 2024 — McMap. All rights reserved.