I have 3 text fields and a button, and when a user presses the button, I would like to check if he has inserted integer values in the first two of them. If yes, then the sum of both of them is shown in the third one. If not, then a message like "error" goes in the third one. How do I make the check?
Here's some code I wrote (it works fine, exept that it doesn't make a type check) :

@Action
   
    public void selfrename() {
        int number1, number2;
       
        jButton1.setText("Show sum");
        number1 = Integer.valueOf( jTextField1.getText() ).intValue();
        number2 = Integer.valueOf( jTextField2.getText() ).intValue();
        jTextField3.setText(Integer.toString(number1 + number2));
 
    }

This is a little peculiar - you're taking two parameters which are never read, but only written to. But no matter, you want to get the integer values or put an error message. Try Integer.parseInt, and wrap it in a try block. If there's a problem with the input, you'll get a NumberFormatException, and you can use the catch block to put the error message in text field 3.
(I suppose you can use valueOf as well - that gives you a boxed Integer, where parseInt gives you a primitive, though I don't know anything about the internals)

Thanks for the quick answer. I just found the solution :]
Here it is working as I want it to:

@Action
   
    public void selfrename() {
        int number1, number2;
        Scanner a=new Scanner(System.in);
        String num1, num2;
        num1 = jTextField1.getText();

        

        Pattern integerPattern = Pattern.compile("^\\d*$");
        Matcher matchesInteger = integerPattern.matcher(num1);
        boolean isInteger = matchesInteger.matches();

        if (isInteger==true)
        {
            jButton1.setText("ït is int");
            number1 = Integer.valueOf(jTextField1.getText()).intValue();
            number2 = Integer.valueOf(jTextField2.getText()).intValue();
        }
 else
        {
            jButton1.setText("it's not int");
 }
    //jTextField3.setText(Integer.toString(number1 + number2));


    }
This article has been dead for over six months. Start a new discussion instead.