How to Calculate Two JTextField’s Value in Java Swing/AWT/SWT/Windows Builder

Last modified date

Here i’ll be discussing with different Calculation type in JTextfield, and also we will discuss how to only accept numbers from  JTextField. So let us assume two textfield example like JTextField feild1 and JTextField feild2.

In Calculation of the textfield’s we must have basic understanding of wrapper classes, something like converting String to int and vice versa.

Let’s look at the below example :

JButton btnCalculate = new JButton("calculate");
btnCalculate.addActionListener(new ActionListener() {
  public void actionPerformed(ActionEvent arg0) {
  // getting text from texfield and converting to double

 try {
 double d1=Double.parseDouble(field1.getText());
 double d2=Double.parseDouble(field2.getText());
// result is displayed in the a label answer ! 


 } catch (NumberFormatException e) {
 // TODO: handle exception
 System.out.println("Invalid number");
btnCalculate.setBounds(150, 227, 89, 23);

By default the textfield field value returns String for setText() and getText() method, so we must use wrapper class logic to store the field value to double and if you look at the point answer.setText() the field also requires a String to display the answer again i used wrapper class concept to convert the double value.

Understanding Wrapper Class

In simple words if you want to convert any String number to number datatype, example like int, double, long etc we must use  parseXXX(String goes here). if we want to convert any number to String just call String.valueOf(your number goes here).

If you look deeper into the above code i have directly called the field1 and field2 and stored in the double values so that the calculation process can be done easier. There are plenty of other ways to calculate the JTextField, but the above process is little easier for the beginners to understand.

You can also write the entire code in single line

 try {
 } catch (NumberFormatException e) {
 System.out.println("Invalid number");

NumberFormatException in Calculation of two JTextField

When we are trying to calculate the field values there is a chance you may have NumberFormatException, for example if we mistakenly entered String in the textfield and trying to calculate the NumberFormatException will be raised and the process of program will be terminated and the point of exception. so it is better recommended to handle the exception using the try catch block.