0

When I run this it will display the two inputs together. For example 1 + 2 will come out to 12. I know that this string has to somehow be changed to an integer but I am lost on how to do so. Any help is greatly appreciated.

private void     
jButton5ActionPerformed(java.awt.event.ActionEvent evt) {                           
jLabel1.setText (String.valueOf(jTextField1.getText() +
jTextField2.getText()));
Sroop
  • 41
  • 1
  • 1
  • 7

2 Answers2

2

Values from JTextFields are Strings. If you want to do arithmetic on them you have to cast them to appropriate Numeric type like Integer or Double.

jLabel1.setText(String.valueOf(Integer.parseInt(jTextField1.getText()) + Integer.parseInt(jTextField2.getText())));

Arqan
  • 376
  • 1
  • 3
  • 14
  • `setText()` method expects a `String` argument, not an `int`. You need to convert `int` to `String` inside parenthesis. – Yousaf Feb 21 '17 at 18:30
0

I know that this string has to somehow be changed to an integer but I am lost on how to do so.

You are right. That's indeed the problem. Extracting a string number to int is very easy to achieve using Integer.parseInt method.

private void     
jButton5ActionPerformed(java.awt.event.ActionEvent evt) {                           
jLabel1.setText (String.valueOf(Integer.parseInt(jTextField1.getText()) +
Initeger.parseInt(jTextField2.getText())));
VHS
  • 9,534
  • 3
  • 19
  • 43