1

我有一个InputVerifierfor ajTextField来检查用户的输入是否是整数。如果不是,我想将其恢复为最后的良好价值。我该怎么做?这是我到目前为止的代码:

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;
    }

}

编辑:以下是我最终用作解决方案的内容。我实际上最初尝试过这个,但它似乎不起作用。我发现错误在测试中。我试图在启动 gui 后立即将文本字段更改为无效值,但它会清空该字段。但是,一旦 gui 启动,文本字段就有焦点,所以我认为它的初始值为 null。随后的更改按预期进行。

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;
    }
}
4

2 回答 2

1

您的问题指向不同的问题,即代码中的注释。您应该在验证后保存旧值,如果当前输入无效,则恢复。你应该打电话text.setText()而不是input.setText()。像这样的东西:

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;
    }
}
于 2010-11-21T16:05:43.697 回答
0

而不是传递JComponent,只需传递字符串值。

于 2010-11-21T16:09:22.247 回答