简体   繁体   English

如何验证textField输入?

[英]How to verify textField input?

I know this shouldn't be too difficult but my searching hasn't led to anything useful yet. 我知道这应该不太困难,但我的搜索尚未找到有用的东西。 All I want to do is make sure the user inputs a positive integer into a textField. 我要做的就是确保用户在textField中输入一个正整数。 I've tried: 我试过了:

public class myInputVerifier extends InputVerifier {
    @Override
    public boolean verify(JComponent jc) {
        String text = ((jTextFieldMTU) jc).getText();
        //Validate input here, like check int by try to parse it using Integer.parseInt(text), and return true or false

        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }
}

So in my main code I want to use this to display "OK" if successful and "Enter a positive number" if not successful. 因此,在我的主代码中,如果成功,我想使用它显示“ OK”,如果不成功,则显示“输入正数”。

Can someone point me in the right direction please? 有人可以指出我正确的方向吗? Thanks! 谢谢!

You could use a try-catch block to check if the input is an integer: 您可以使用try-catch块来检查输入是否为整数:

try {
    int i = Integer.parseInt(input);
    // input is a valid integer
}
catch (NumberFormatException e) {
    // input is not a valid integer
}

String has a matches method you can use with regular expressions to see if the contents match a particular pattern. 字符串具有match方法,您可以将其与正则表达式一起使用,以查看内容是否与特定模式匹配。 The regular expression for positive integers is ^[1-9]\\d*$ so you can use it like this... 正整数的正则表达式为^ [1-9] \\ d * $,因此您可以像这样使用它...

boolean matches = text.matches("^[1-9]\d*$");

if(matches){
   //Do something if it is valid
}else{
   //Do something if it is not
}

I suggest you use try catch. 我建议您使用try catch。 Catch the NumberFormatException. 捕获NumberFormatException。 In this way you check if the text can be parsed to an integer. 这样,您可以检查文本是否可以解析为整数。 If not you can display an error message to the user. 如果没有,您可以向用户显示错误消息。 After that you can us an if else statement to check if the number is positive if not positive you can give the user an error message. 之后,您可以使用if else语句检查数字是否为正,如果不为正,则可以向用户显示错误消息。 I suggest you research try catch if you don't know it. 如果您不知道,建议您研究尝试捕获。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM