简体   繁体   中英

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. 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.

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 {
    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. The regular expression for positive integers is ^[1-9]\\d*$ so you can use it like this...

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. Catch the 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. I suggest you research try catch if you don't know it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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