Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Setting Up a JTextField to only accept Integers - Solution! (with Questions)

 
Declan Dee
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

You can type only integers and nothing else



Any explination? - Thanks in advance

Good to finally have a solution!

You have no idea how long I was looking for this!
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Congratulations on getting it to work!

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.
 
pete stein
Bartender
Posts: 1561
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Other possible Swing solutions: use a JFormattedTextField instead of a JTextField, or you could use a JTextField and add a DocumentFilter to the PlainDocument that the JTextField holds.
 
Michael Dunn
Ranch Hand
Posts: 4632
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
> I spent ages on several forums looking for a solution but I could not find anything.

you need to sharpen your research skills

JTextField is a Swing component
the ranch has a Swing Forum
the Swing forum has an FAQ
the FAQ has this listing

NumericTextField - how to create a text field that only accepts numbers as input
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Michael Dunn wrote:... NumericTextField - how to create a text field that only accepts numbers as input

Nice!

(Like I said above, "I don't know the 'best' way...")
 
Declan Dee
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Of course it can be made even simpler:



However there is one BIG problem. When using this you can enter a minus number and it will be accepted
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic