InputVerifier stealing focus

183 Views Asked by At

I have a problem with an InputVerifier stealing the focus in my app. When I click on the textfield that uses this verifier, I can't click anywhere else unless I fill the field with 4 digits (the verifier is here to prevent anything else than digits is entered, and there must be 4 of them).

Here is my code :

public class NumberVerifier extends InputVerifier {

public boolean verify(JComponent input) {
    String text = ((JTextField) input).getText();
        if((text.length()==4) && isNumeric(text)){
            return true;
        }else{
            return false;
        }
}

    public static boolean isNumeric(String str)
    {
      return str.matches("[0-9]+\\.?");
    }

}

Is there any way to prevent this from happening ?

1

There are 1 best solutions below

0
JJF On

You can simply accept the input as valid if it matches your 'exactly 4 numeric digits' or if it is empty (length is 0).

public boolean verify(JComponent input) {
    String text = ((JTextField) input).getText();
        // if text is 4 digits or it's empty
        if(((text.length()==4) && isNumeric(text)) || (text.length()==0)){
            return true;
        }else{
            return false;
        }
}