-1

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 ?

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
DevBob
  • 835
  • 2
  • 9
  • 29
  • Then the verifier is doing its job. What behavior do you want to happen if the JTextField is not complete and the user wants to leave the field? – Hovercraft Full Of Eels Jan 08 '16 at 13:57
  • per the Verfier API: `"support smooth focus navigation through GUIs with text fields. Such GUIs often need to ensure that the text entered by the user is valid (for example, that it's in the proper format) **before allowing the user to navigate out of the text field**."` so again, it's doing exactly what you expect it should be doing. – Hovercraft Full Of Eels Jan 08 '16 at 13:59
  • Note, you could override the verifier's `public boolean shouldYieldFocus(...)` method if you want a different behavior. – Hovercraft Full Of Eels Jan 08 '16 at 14:01
  • Please have a look at kleopatra's answer [here](http://stackoverflow.com/a/7009241/522444) for more on the pro's and con's of InputVerfier. – Hovercraft Full Of Eels Jan 08 '16 at 14:05
  • 1
    Sounds like you probably want a `JFormattedTextField` instead; see [`JFormattedTextField.setFocusLostBehavior(...)`](https://docs.oracle.com/javase/8/docs/api/javax/swing/JFormattedTextField.html#setFocusLostBehavior-int-). By the way, `if(condition) { return true; } else { return false; }` is a verbose way of saying `return condition;` – Holger Jan 08 '16 at 17:54

1 Answers1

1

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;
        }
}
JJF
  • 2,681
  • 2
  • 18
  • 31