0

I'm creating a GUI for a club and am trying to set up a test so that when a new user is prompted to input their name, they will not be able to input any numeric values.

Here is the code I have so far:

else if((this.jTextFieldName.getText() ){
        errorMessage = "Name is not acceptable";
        this.jTextFieldNameActionPerformed(requestFocusInWindow());
}

The space after getText() in the first line is where I need to input a test but I can't find a way to do this that works. Can anyone help?

mKorbel
  • 109,525
  • 20
  • 134
  • 319

4 Answers4

4

The best way in swing is if you are using PlainDocument as document for your textComponent. It's to use a DocumentFilter. Take a look in how to do it in Text Component Features implementing a DocumentFilter. You have to override ìnsertString method then there you can use your regex. Here you have an example using DocumentFilter.

Community
  • 1
  • 1
nachokk
  • 14,363
  • 4
  • 24
  • 53
1

Why not try with a regex?

else if(this.jTextFieldName.getText().matches(".*\\d+.*") ){

AntonH
  • 6,359
  • 2
  • 30
  • 40
0

If you can then go for it

jTextField.addKeyListener(new KeyAdapter() {
    public void keyTyped(KeyEvent e) {
      char c = e.getKeyChar();
      if (!((c >= 'a') && (c <= 'z') || (c >= 'A') && (c <= 'Z') ||
         (c == KeyEvent.VK_BACK_SPACE) ||
         (c == KeyEvent.VK_DELETE))) {
        getToolkit().beep();
        //JOptionPane.showMessageDialog(rootPane, "Enter only Alphabets");
        e.consume();
      }
    }
  });
ravibagul91
  • 20,072
  • 5
  • 36
  • 59
0

Try the regex ^[0-9]+$.

You can implement it like this:

this.jTextFieldName.getText().matches("^[0-9]+$")
The Guy with The Hat
  • 10,836
  • 8
  • 57
  • 75
Nags
  • 1
  • 2