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?
 
objectsCommented:
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());
0
 
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
0
 
amaiAuthor Commented:
Hi objects,

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

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

David
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.