Win a copy of Five Lines of Code this week in the OO, Patterns, UML and Refactoring forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Bear Bibeault
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Tim Cooke
  • Liutauras Vilda
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • fred rosenberger
  • salvin francis
Bartenders:
  • Piet Souris
  • Frits Walraven
  • Carey Brown

textfield that accepts only numbers???

 
Ranch Hand
Posts: 88
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi!
I want a textfield(awt component) to accept only numbers.how would i do it?
thanks!
raymond
 
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is not possible to create a java.awt.TextFiled that accepts only numbers. Rather you would call .getText on the TextField object and validate the String returned to see if it describes a valid number.
Hope this helps.
 
Sheriff
Posts: 3341
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can extend TextField and add an KeyListener to it. The action method on the KeyListener needs to validate that the key entered was a numeric key.
 
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Heres a textfield that will only allow numbers and the spacebar

textfield.addKeyListener(new KeyAdapter()
{
public void keyTyped(KeyEvent ke)
{
char c = ke.getKeyChar();
if((!(Character.isDigit(c))) && // Only digits
(c ! '\b') ) // For backspace
{
ke.consume();
}
}
public void keyReleased(KeyEvent e){}
public void keyPressed(KeyEvent e){}
});
 
Ranch Hand
Posts: 732
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
why extend?
just add a KeyListener to your textfield (or a textListener).
if the user enterd something that isnt a number then just consume the event.
 
    Bookmark Topic Watch Topic
  • New Topic