Search code examples
javaswingvalidationintegerjtextfield

Determine if a JTextField contains an integer


I'm making a word guessing game. The JTextField can't be empty, can't be longer or smaller than 5 and cannot contain numbers. How do I do the last part?

@Override
public void actionPerformed(ActionEvent e) {
    if (text.getText().isEmpty()) {
        showErrorMessage("You have to type something");
    } else if (text.getText().length() != 5) {
        showErrorMessage("Currently only supporting 5-letter words");
    } else if (contains integer){
        showErrorMessage("Words don't contain numbers!");
    } else {
        r.setGuess(text.getText());
    }
}

Solution

  • Rather than explicitly checking for numbers, I would suggest whitelisting characters which are allowed. Would letters with accents be allowed, for example? Both upper and lower case? Punctuation?

    Once you've worked out your requirements, I suggest you express them as a regular expression - and then check whether the text matches the regular expression.

    For example:

    private static final Pattern VALID_WORD = Pattern.compile("^[A-Za-z]*$");
    
    ...
    
    if (!VALID_WORD.matcher(text.getText()).matches()) {
       // Show some appropriate error message
    }
    

    Note that I haven't included length checks in there, as you're already covering those - and it may well be worth doing so in order to give more specific error messages.

    You might also want to consider preventing your text box from accepting the invalid characters to start with - just reject the key presses, rather than waiting for a submission event. (You could also change the case consistently at the same time, for example.) As noted in comments, JFormattedTextField is probably a good match - see the tutorial to get started.