Search code examples
javaswingjtextfieldsettext

Dynamically setting text in JTextField in Java


I am creating an account creation tool for my software. In this tool, it asks you for your name, email address, etc., and I use JTextFields to collect this information.

I wanted to try something different and have invalid information fixed in real time. I have my code set up so that whenever a the text field has changed, a method is run to remove unwanted characters and do some other things. The code sort of looks like this:

private void firstNameUpdate(){
    String name = firstNameField.getText();
    int pos = firstNameField.getCaretPosition();
    if (!name.equals("")){
        name = name.replaceAll("[^a-zA-Z]", "").toLowerCase();
        if (!name.equals("")){
            name = name.substring(0, 1).toUpperCase() + name.substring(1);
            validFirstName = true;
        } else {
            validFirstName = false;
        }
    } else {
        validFirstName = false;
    }
    firstNameField.setText(name);
    firstNameField.setCaretPosition(pos);
}

The code, 'firstNameField.setText(name);' is what causes the error. I know everything else in the method works because I tried having it print out to the console instead.

All sources that I have seen say that this should work. What am I doing wrong?


Solution

  • For real-time filteration of text components, you should be using a DocumentFilter.

    Take a look at Implementing a DocumentFilter and these examples.

    The likely cause is you are getting a concurrent modification error, where you are trying to modify the underlying fields document while it is been modified.