开发者

Adding Textboxes in Form(JAVA, Netbeans 7)

开发者 https://www.devze.com 2023-03-13 22:50 出处:网络
I am new to the realm of JAVA and I am starting to play around. I have made a form in Netbeans with 3 Text Boxes. I am then trying to add those the first two text boxes and place the sum in the third

I am new to the realm of JAVA and I am starting to play around. I have made a form in Netbeans with 3 Text Boxes. I am then trying to add those the first two text boxes and place the sum in the third once a button is clicked. I have the following code but it is listing the output together(not as a sum).

Example: 2+2 = 22, 3+34 = 334

My Code is below:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
开发者_如何学运维    String x = jTextField1.getText();
    String y = jTextField2.getText();
    jTextField3.setText(x + y);
}


It is because when you use + operator for String it will not add it but concat 2 strings because it is not necessary that string always holds a number. So you have to first convert your string to int (or any other numeric type) and then do the sum.

Try this:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
  try{
    int x = Integer.parseInt(jTextField1.getText());
    int y = Integer.parseInt(jTextField2.getText());
    jTextField3.setText((x + y)+"");
  catch(Exception e){
    //-- NumberFormatException hadling
  }
}

Notice the try..catch(). It is because some can write a string which can not be cast to int like "a324ad".


The + operator for string data type concatenates the strings. If you are trying to add the two numbers entered in the text boxes, you need to convert then to a numeric data type. For Integer, you can use Integer.parseInt().

Try

String x = jTextField1.getText();
String y = jTextField2.getText();
jTextField3.setText(Integer.toString(Integer.parseInt(x) + Integer.parseInt(y)));
0

精彩评论

暂无评论...
验证码 换一张
取 消