所以,我正在尝试制作一个简单的程序。我想用任何东西(符号,数字或单词)填充jtextfield
,但是当我单击jubutton
时,会出现一个消息对话框
这是我的代码,但它没有按我想要的方式工作,因为当我在数字后输入字符时,消息对话框没有显示
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("");
}
使用正则表达式
if(!txtphone.getText().matches("\d+")){
JOptionPane.showMessageDialog(rootPane, "Input must number");
txtphone.setText("");
}
DocumentFilter
是您想要的更好选择。你在SO中有很多例子。检查这个。
目前您检查JTextfield
中是否有数字,但您想知道其中是否只有数字:
if (!txtphone.getText().matches("[0-9]+"))
{
JOptionPane.showMessageDialog(rootPane, "Input must number");
txtphone.setText("");
}