检查JTextField是否仅包含特定的允许字符

时间:2014-03-11 13:31:01

标签: java regex string swing jtextfield

我有一个JFormattedTextField,我只想插入字母数字字符。我正在尝试使用此代码在用户键入不允许的字符时启动JDialog,以防万一从JFormattedTextField获取字符串。当我运行此代码时,键入符号时不会出现JOptionPane。我知道我的代码有问题,但由于我的经验不足,我无法识别它。我将不胜感激。

提前谢谢

static JFormattedTextField indivname = new JFormattedTextField();

final String individ = indivname.getText();

indivname.getDocument().addDocumentListener(new DocumentListener() {
    public void changedUpdate(DocumentEvent e) {
        warn(individ);
    }
    public void removeUpdate(DocumentEvent e) {
        warn(individ);
    }
    public void insertUpdate(DocumentEvent e) {
        warn(individ);
    }       
    public void warn(String textcheck) {
        textcheck = indivname.getText();
        boolean match = textcheck.matches("[a-zA-Z0-9]+"); 

        if (match=false) {                            
            JOptionPane.showMessageDialog(null, "You have inserted restricted characters (Only alphanumeric characters are allowed)", "Warning", JOptionPane.WARNING_MESSAGE);                   
        }

        if (match=true) {                            
            textcheck = individ ;                     
        }                   
    }
});

3 个答案:

答案 0 :(得分:2)

您正在使用赋值运算符=而不是==语句中的比较if

 if (match = false) {

 ...

 if (match=true) {

表达式match = false会导致match获得false值,整个表达式始终返回false

你应该用以下内容替换:

 if (!match) {
     JOptionPane.showMessageDialog(null, "You have inserted restricted characters (Only alphanumeric characters are allowed)", "Warning", JOptionPane.WARNING_MESSAGE);
 } else { // instead of if(match)
     textcheck = individ;
 }

直接使用match的值来确定要执行的分支。

答案 1 :(得分:2)

使用if (match=false),您将false值分配给match,然后if检查其值,因为它是false,所以跳过此块。

if(match=true)相同。

使用

  • if(match==false)或更好,以避免==使用if (!match)
  • 时出现的错误
  • if(match==true)或更好if(match)

答案 2 :(得分:1)

使用JFormattedTextField的目的是编辑输入的文本,以便不能添加无效字符。

阅读Swing教程中有关如何使用Formatted Text Fields的部分以获取更多信息和示例。您可能想要Mask Formatters上的部分。

相关问题