Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Integer Text field  RSS feed

 
Rajasree R
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To validate an integer text field ,which of these two methods are better?
1.
protected void processComponentKeyEvent(KeyEvent ke) {
if(ke.getKeyCode() == KeyEvent.VK_DELETE ||
ke.getKeyCode() == KeyEvent.VK_BACK_SPACE ||
ke.getKeyCode() == KeyEvent.VK_UP ||
ke.getKeyCode() == KeyEvent.VK_DOWN ||
ke.getKeyCode() == KeyEvent.VK_LEFT ||
ke.getKeyCode() == KeyEvent.VK_RIGHT)
super.processComponentKeyEvent(ke);
char c = ke.getKeyChar();
if(!((c >= '0' && c <= '9') || (c == '-'))) {
ke.consume();
} else {
super.processComponentKeyEvent(ke);
}
}


2.Creating a document object extending from PlainDocument of textfield?
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24215
37
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Welcome to JavaRanch!

You may not have read our naming policy on the way in. It requires that you use a full, real (sounding) first and last name for your display name. Just one name isn't enough. You can change your display name here. Thanks!

In any case: a third alternative, superior to either of these, is to use the JFormattedTextField class. See this article for details.
 
Rajasree R
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Thank you for the response.
What can I do if i need to set a minimum and maximum value for the text field.When I use textfield's document object i used to check it there in insertString method.Is there a better way for this?
Thank u in advance
Rajasree
 
Michael Dunn
Ranch Hand
Posts: 4632
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
if you want integer values only, and a minimum/maximum, perhaps a JSpinner might be better for you
 
Rajasree R
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Sorry..i dont want to use a spinner.I want the field to have the look of a normal textfield..Any other option for this?
 
Craig Wood
Ranch Hand
Posts: 1535
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I recommend either a DocumentFilter (tutorial has an example) or an InputVerifier (example in api). The DocumentFilter is similiar to the PlainDocument approach but lighter weight.
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!