We help IT Professionals succeed at work.

Check if user has entered only integer

amai
amai asked
on
Medium Priority
213 Views
Last Modified: 2010-03-31
Hi,

I'm using javax.swing.JTextField to get user to enter some data. How can I make sure that user only enters integer for processing?

Thanks
Comment
Watch Question

Hi,

try {
    int val = Integer.parseInt(yourTextField.getText());
    System.out.println("User entered integer value");
}
catch (Exception e) {
    System.out.println("User entered invalid integer value");
    e.printStackTrace();  // I forgot what Exception does it throw, if I am not mistaken, NumberFormatException
}

Thanks
David
Java Developer
CERTIFIED EXPERT
Top Expert 2010
Commented:
Use a custom document with your text field

public class IntegerDocument extends PlainDocument
{
     public IntegerDocument()
     {
          super();
     }

     public void insertString(int offset, String s, AttributeSet attributeSet)
          throws BadLocationException
     {
          try
          {
               Integer.parseInt(getText(0, offset) + s + getText(offset, getLength()-offset));
               super.insertString(offset, s, attributeSet);
          }
          catch (Exception ex)
          {
               Toolkit.getDefaultToolkit().beep();
          }
     
     }
}


and use it like this:

JTextField tf = new JTextField(new IntegerDocument());

Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts

Author

Commented:
Hi objects,

I don't really understand why must you use offset, and later insertString. Can you explain?
Thanks!
Mick BarryJava Developer
CERTIFIED EXPERT
Top Expert 2010

Commented:
offset tells where to insert entered text inteo existing string
and you only want to insert the text if it is successfully paresed as an int ie. if its not an int then don't insert
Mmm....

I think that objects proposed you a better solution ;) so use it.

David
Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.