1

I made a GUI which basically adds the numbers from the two textfield. The problem is, if I leave the other textfield blank and the other textfield has a number, the result textfield is not updating.

public class AdditionGui extends JFrame implements ActionListener { private TextField tf1 , tf2 , tf3; private Label sign, equalsign; private int sum = 0; AdditionGui(){ setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(new FlowLayout()); tf1 = new TextField(5); add(tf1); tf1.addActionListener(this); sign = new Label("+"); add(sign); tf2 = new TextField(5); add(tf2); tf2.addActionListener(this); equalsign = new Label("="); add(equalsign); tf3 = new TextField(5); add(tf3); setTitle("Sum of two numbers"); setSize(220,120); setVisible(true); } public void actionPerformed(ActionEvent ae) { int val1 = Integer.parseInt(tf1.getText()); int val2 = Integer.parseInt(tf2.getText()); sum = val1 + val2; tf3.setText("" + sum); } } 

1 Answer 1

1

A blank text field means its contents cannot be parsed to an Integer. In that case this line of your code will throw NumberFormatException (if tf1 is blank).

int val1 = Integer.parseInt(tf1.getText()); 

In your actionPerformed() method, check that getText() returns a number.
I suggest setting a blank text field to zero, for example:

String text1 = tf1.getText(); if (text1.length() == 0) { text1 = "0"; } int val1 = Integer.parseInt(text1); String text2 = tf2.getText(); if (text2.length() == 0) { text2 = "0"; } int val2 = Integer.parseInt(text2); int sum = val1 + val2; tf3.setText(Integer.toString(sum)); 

Now something for you to think about.
What happens if the user enters a non-digit into one of the text fields?

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.