DocumentListener Java, How do I prevent empty string in JTextBox?

As @HFOE suggests, InputVerifier is the right choice, but verify() “should have no side effects.” Instead, invoke calcProduct() in shouldYieldFocus().

 /**
 * @see http://stackoverflow.com/a/11818946/230513
 */
private class MyInputVerifier extends InputVerifier {

    private JTextField field;
    private double value;

    public MyInputVerifier(JTextField field) {
        this.field = field;
    }

    @Override
    public boolean shouldYieldFocus(JComponent input) {
        if (verify(input)) {
            field.setText(String.valueOf(value));
            calcProduct();
            return true;
        } else {
            field.setText(ZERO);
            field.selectAll();
            return false;
        }

    }

    @Override
    public boolean verify(JComponent input) {
        try {
            value = Double.parseDouble(field.getText());
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }
}

Leave a Comment