javainputverifier

Revert jTextField to last good value


I have an InputVerifier for a jTextField to check and see if the input from the user is an integer. If it is not, I want to revert it to the last good value. How do I to this? Here is the code I have so far:

class IntegerVerifier extends InputVerifier {

    public boolean verify(JComponent input) {
            JTextField text = (JTextField)input;
            String old = text.getText();
        try {
            Integer.parseInt(text.getText().trim());
        } catch (NumberFormatException e) {
            // this does not work b/c input is not a TextField
            input.setText(old); 
        }
        return true;
    }

}

EDIT: Below is what I ended up using as the solution. I had actually tried this initially, but it appeared to not be working. I discovered the error was in the testing. I tried to change the textfield to an invalid value right after starting the gui, but it would blank out the field. However, the textfield had focus as soon as the gui started, so it's initial value was null I think. Subsequent changes behaved as expected.

class IntegerVerifier extends InputVerifier {
    public boolean verify(JComponent input) {
        JTextField text = (JTextField) input;
        String old = text.getText();
        try {
            Integer.parseInt(text.getText().trim());
        } catch (NumberFormatException e) {
            text.setText(old);
            //return false; // don't use this otherwise it won't revert the value
        }
        return true;
    }
}

Solution

  • Your question points to different problem, that the comment in your code. You should save the old value, after it is verified, and revert, if the current input is invalid. You should call text.setText() and not input.setText(). Something like this:

    class IntegerVerifier extends InputVerifier {
        String lastGood = "";
        public boolean verify(JComponent input) {
            JTextField text = (JTextField)input;
            String value = text.getText().trim();
            try {
                Integer.parseInt(value);
                lastGood = value;
            } catch (NumberFormatException e) {
                text.setText(lastGood);
                // assumed it should return false
               return false;
            }
            return true;
        }
    }