This week's book giveaway is in the General Computing forum.
We're giving away four copies of Arduino in Action and have Martin Evans, Joshua Noble, and Jordan Hochenbaum on-line!
See this thread for details.
The moose likes Swing / AWT / SWT and the fly likes Integer Text field Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


JavaRanch » Java Forums » Java » Swing / AWT / SWT
Reply Bookmark "Integer Text field" Watch "Integer Text field" New topic
Author

Integer Text field

Rajasree R
Greenhorn

Joined: May 23, 2005
Posts: 12
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
Marshal

Joined: Jul 08, 2003
Posts: 24081
    
  15

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.


[Jess in Action][AskingGoodQuestions]
Rajasree R
Greenhorn

Joined: May 23, 2005
Posts: 12
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

Joined: Jun 09, 2003
Posts: 4632
if you want integer values only, and a minimum/maximum, perhaps a JSpinner might be better for you
Rajasree R
Greenhorn

Joined: May 23, 2005
Posts: 12
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

Joined: Jan 14, 2004
Posts: 1535
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.
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: Integer Text field
 
Similar Threads
urgent.event consume
Problem with KeyEvent and VK_TAB
KeyEvent - Keypress
How to make textfield only accept numbers?
VK_TAB event not working