Search code examples
javaregexstringswingjtextfield

Checking if JTextField contains only specific allowed characters


I have a JFormattedTextField where I want only alphanumeric characters to be inserted. I am trying to use this code to launch a JDialog when the user types a non-allowed character, and in case everything is ok to get the string from the JFormattedTextField. When I run this code, no JOptionPane will come up when I type a symbol. I am aware that there is something wrong with my code, but due to my little experience I cannot identify it. I would appreciate some help.

Thank you in advance

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 ;                     
        }                   
    }
});

Solution

  • You are using the assignment operator = instead of the comparison == in lines with the if statements:

     if (match = false) {
    
     ...
    
     if (match=true) {
    

    The expression match = false results in match getting a false value and the whole expression always returning false.

    You should replace those with:

     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;
     }
    

    which uses the value of match directly to determine what branch to execute.