Setting Up a JTextField to only accept Integers - Solution! (with Questions)
Declan Dee
Greenhorn
Joined: May 04, 2010
Posts: 20
posted
0
Hi,
I was asked during my course to set up a JTextfield to make sure that only integers are accepted. I spent ages on several forums looking for a solution but I could not find anything.
Luckily I manged to find a solution, but unfortunatly I am not 100% what I have typed and I would love to know excatly what it is. Its works perfectly by the way.
Integer's parseInt method throws a NumberFormatException if the String parameter cannot be parsed as an int. This is the exception you're catching if the String returned by getText contains something other than digits.
But...
There are ways to do this without throwing an exception. I don't know the "best" way, but one approach is to consider that a String is a sequence of characters, and the Character class has a method isDigit. You could test the user's input and keep asking them to correct it until it satisfies your condition.
"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer sscce.org