Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

How to validate a textbox to accept numbers only

How can I validate a textbox to accept numbers only?

private class ButtonHandler implements ActionListener
{
     @Override
     public void actionPerformed(ActionEvent ae) 
     {
          JButton btn = (JButton)ae.getSource();
          if (btn == btnGenerate) 
          {
              if (txtRow.getText().equals("") || txtCol.getText().equals("")) 
              {
                  JOptionPane.showMessageDialog(null, "Please enter number");
              }
           }
}

I have this so far, but it allows characters, but all I want is numbers.

2 Answers

Ken Alger
STAFF
Ken Alger
Treehouse Teacher

Khaleel;

I would look at the JFormattedTextField options.

Ken

Thanks I'll have a look into that.

Craig Dennis
STAFF
Craig Dennis
Treehouse Teacher

Regular expressions might make your head spin a bit, but they are great for things like this.