This week's book giveaway is in the Kotlin forum.
We're giving away four copies of Kotlin in Action and have Dmitry Jemerov & Svetlana Isakova on-line!
See this thread for details.
Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

wanting to only enter numbers in a textfield  RSS feed

 
Candy Bortniker
Ranch Hand
Posts: 123
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I want to create a textfield that will only allow the user to enter numbers. I have some code that I think should do this but it isn't working, which obviously means I am doing something incorrectly. I'm hoping one of you know how to fix this problem. I am getting inside the if statement because I get the printline but the A is still entered in the textfield.
Here is the code I have:
 
Michael Morris
Ranch Hand
Posts: 3451
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey Candy,
The easiest way to do this is to use a custom document model for the text component, something like this:

That loops thru all of the inserted chars (usually there is just one) and rings the system bell and returns without inserting the text into the component if there is a non digit char in the input, otherwise it copies it into the document model.
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Moving to Swing/AWT forum.
 
Gregg Bolinger
Ranch Hand
Posts: 15304
6
Chrome IntelliJ IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You might also take a look at the JFormattedTextField and using an InputVerifier.
Both those links show examples in the API docs.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!