0

I've got a JTextField. Is there any way I can restrict it to only allow the user to insert numbers in to it?

Currently I've got a button connected to the Text Field so when its pressed it does getText() and converts it to a int, obviously this becomes a problem if the user does not submit an int in the first place.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • Have a look at this question: http://stackoverflow.com/questions/14215847/jtextfield-validation-for-numbers-and-one-decimal-point/14219756#14219756 – Branislav Lazic Jun 12 '13 at 10:00
  • Or a `JFormattedTextField` as shown [here](http://stackoverflow.com/a/13424140/1076463) – Robin Jun 12 '13 at 12:48

2 Answers2

2

You can use a DocumentFilter, it is effective in your case. Here is the tutorial to implement it.

AllTooSir
  • 48,828
  • 16
  • 130
  • 164
2
  try {
     int x = Integer.parseInt(input);
     isInt = true;
 }
  catch(NumberFormatException nFE) {
     isInt=false;
 }

You could validate the button input if isInt is true. Hope it helps!

aran
  • 10,978
  • 5
  • 39
  • 69
  • This is totally my bad. Didn't understand the question correctly. Answer edited. – aran Jun 12 '13 at 10:27
  • done! no worries, I guess I should read questions twice. – aran Jun 12 '13 at 10:57
  • 1
    *"I guess I should read questions twice"* And I should be more careful in my reading of comments and edited answers. ;) +1 – Andrew Thompson Jun 12 '13 at 10:59
  • thanks Andrew, although your approach is more appropiate for this issue. +1 on your comments. Gosh this seems a love history. Where's the pony and the rainbow?? – aran Jun 12 '13 at 11:01
  • *"Where's the pony and the rainbow"* The pony is playing the violins you hear, the rainbow .. I'm not sure, but it's night where I am. :) – Andrew Thompson Jun 12 '13 at 11:05