0

So, I'm trying to make a simple program. I want to fill the jtextfield with anything (symbols,number or words) but when I click on jubutton there's a message dialog appears

This is my code,but it's not working as I want,because when I enter a character after a number the message dialog didn't shown up

if (!txtphone.getText().contains("1")&&!txtphone.getText().contains("2")&&!txtphone.getText().contains("3")&&!txtphone.getText().contains("4")&&!txtphone.getText().contains("5")&&!txtphone.getText().contains("6")&&!txtphone.getText().contains("7")&&!txtphone.getText().contains("8")&&!txtphone.getText().contains("9")&&!txtphone.getText().contains("0")) 
{
    JOptionPane.showMessageDialog(rootPane, "Input must number");
    txtphone.setText("");
}
Soma
  • 861
  • 2
  • 17
  • 32
  • are you sure you want to allow characters in your textfield as long as there are also digits ? because it looks like your textfield should represent telephone numbers... do you really just want to check if there are any numbers or do you want the textfield to only accept numbers ? – dehlen Jan 03 '14 at 13:20
  • The `contains` method looks for a character appearing anywhere in the string, so if you've typed "1a" then `.contains("1")` will return `true`. Is that what you want? – Paolo Jan 03 '14 at 13:21
  • Use a `JFormattedTextField` – Paul Samsotha Jan 03 '14 at 13:23

3 Answers3

0

DocumentFilter is a better choice for what you want. You have a lot of examples in SO. Check this one.

Community
  • 1
  • 1
Sergi
  • 579
  • 3
  • 14
0

Currently you check if there are numbers in the JTextfield, but you want to know if there are ONLY numbers in it:

if (!txtphone.getText().matches("[0-9]+")) 
{
    JOptionPane.showMessageDialog(rootPane, "Input must number");
    txtphone.setText("");
}
EisenRatte
  • 542
  • 5
  • 12
0

Use regex

if(!txtphone.getText().matches("\\d+")){
    JOptionPane.showMessageDialog(rootPane, "Input must number");
    txtphone.setText("");
}
AJ.
  • 4,526
  • 5
  • 29
  • 41