简体   繁体   中英

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

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.

With if (match=false) you are assigning false value to match , and then if checks its value, and since it is false this block is skipped.

Same about if(match=true) .

Use

  • if(match==false) or better to avoid mistakes with == use if (!match)
  • if(match==true) or better if(match) .

The point of using a JFormattedTextField is to edit the text as it is entered so that no invalid character can be added.

Read the section from the Swing tutorial on How to Use Formatted Text Fields for more information and examples. You probably want the section on Mask Formatters .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM