Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

How to make textfield only accept numbers?  RSS feed

 
Jon Mattson
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How do I make a textfield in which you only can type numbers into, like pressing a letter wouldn't do anything. I've checked the FormattedTextField tutorial but I don't really understand how to use it to make this.

Any ideas?
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You could use a DocumentListener.
 
Jeff Albertson
Ranch Hand
Posts: 1780
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Either JFormattedTextField or DocumentFilter
 
Reed Spool
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, I'm not sure of the exact syntax but could you use the 'try' and 'catch' stuff with a Integer.parseInt()? p.s. if this is rediculous, i'm new. if this works, I'm glad i could help
 
Tony Morris
Ranch Hand
Posts: 1608
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You would write your own Document.
Here's an example I prepared earlier: http://www.xdweb.net/~dibblego/utilities/power/
I'd have to dig around to find the source.
 
Chad Clites
Ranch Hand
Posts: 134
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I use this bit:
 
Jeff Albertson
Ranch Hand
Posts: 1780
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Chad Clites:
I use this bit:


Unfortunately, this doesn't work that well: what if the user is *pasting* into the textfield with Ctrl+V? My rule of thumb is to avoid key listeners.
 
Chad Clites
Ranch Hand
Posts: 134
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Hmm..that's one thing I really enjoy about this place. Inevitably, someone comes up with a scenario I had not considered.

Ok, then a caveat. If there is no danger of a user merely cutting and pasting data, then my method will work. If there is a danger of cut-and-paste, then Jeff and Tony have viable options (which I myself will be looking into).
[ February 16, 2006: Message edited by: Chad Clites ]
 
Nageswar Kakolla
Ranch Hand
Posts: 71
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Use JFormattTextField and MaskFormatter

PHONE_NUMBER = new MaskFormatter();

JTextField textOnly = new JTextField(PHONE_NUMBER);

this will do and you can use textOnly
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!