Check if user has entered only integer

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
amaiAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

suprapto45Commented:
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
Mick BarryJava DeveloperCommented:
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());

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
amaiAuthor Commented:
Hi objects,

I don't really understand why must you use offset, and later insertString. Can you explain?
Thanks!
Mick BarryJava DeveloperCommented:
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
suprapto45Commented:
Mmm....

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

David
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.