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;
Heisenbug
  • 38,762
  • 28
  • 132
  • 190
Bugster
  • 1,552
  • 8
  • 34
  • 56

1 Answers1

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());
Heisenbug
  • 38,762
  • 28
  • 132
  • 190
  • 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? – Bugster Dec 26 '11 at 17:40
  • 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? – Bugster Dec 26 '11 at 17:49
  • you should include javax.swing.JFormattedTextField – Heisenbug Dec 26 '11 at 17:52