TextField Applet Adding Two Numbers


public class TwoNumbers extends Applet implements ActionListener

Observe, the class TwoNumbers extends Applet (not Frame) and as usual implements ActionListener for event handling.

setLayout(new GridLayout(3, 2, 10, 15));
setBackground(Color.cyan);

The applet is set with GridLayout of 3 rows, 2 columns, 10 horizontal and 15 vertical gaps. For an attractive display purpose, a background of predefined color cyan is set.

Three text fields are created, firstNum, secondNum and resultNum. The secondNum (where the user enters the second number) is given the action (with addActionListener()). Whenever, the user presses enter key, the event handling takes place and the sum of two number is displayed in the resultNum field.

add(new Label(“Enter First Number”));

For display purpose of what for the text filed is meant, three anonymous objects of Label component are created and added. Using anonymous objects saves memory on the client machine. The above statement would have been like this also.

Label lab1 = new Label(“Enter First Number”);
add(lab1);

In the above statement, a memory of 4 bytes for Label object lab1 is wasted.

String str1 = firstNum.getText();
double fn = Double.parseDouble(str1);

The getText() method of TextField returns always a string of what user enters in the text filed whether it may be a name, password or a number. For our calculation purpose, the number in the form of string is converted to a double value. This is done with parsing operation using parseDouble() method.

double sn = Double.parseDouble(secondNum.getText());

In the earlier statement, string str1 is used as temporary variable to carry the data to the parseDouble() method. Even this variable can be avoided by passing direct getText() method to the parseDouble() method. In realtime, practice, the programmer does like this only and avoids number of lines of code and also improves the performance.

resultNum.setText(“Sum is ” + (fn+sn));

With setText() method, the value is displayed in the resultNum field. Remember, the setText() method requires a string as parameter. fn+sn when concanated to “Sum is ” becomes a string. Any stirng concatenated with a data type or any other value, results in a string. The following statement raises compilation error.

resultNum.setText(fn+sn);

Then how to do display only fn+sn in the text field. Convert it into a string, using valueOf() method of String class and then pass as follows.

String str = String.valueOf(fn+sn);
resultNum.setText(str);

Alternatively, in a single statement, it could done as follows avoiding the string str.

resultNum.setText(String.valueOf(fn+sn));

For other explanation of the program, refer to the application Java TextField – User Name Password Validation.

The migration steps from application to applet are available at Java AWT Radio Buttons – Applet GUI.

13 thoughts on “TextField Applet Adding Two Numbers”

  1. how to put only 10 textfield boxes with one result textfield and with a submit button which will show the average of the first 10 numbers entered

  2. How to W.A.P in java containing three textfield, 1st textfield accepts lastname and 2nd textfield accepts firstname and onclick of button full name is displayed in 3rd textfield ?

  3. Sushil kumar singh

    Can you help me
    i want to create an applet prog. In which there are three texrfield for number1,number2,result, One button for display and one list in which all arithmatic operator. When i press only one time a display buttun then result will be show in result textfield.

    1. I got a ready made code for application. Just change to an applet.

      // a program that uses a combination of buttons and text fields.

      // to do arithmetic operations using buttons and displaying the result in text field.

      import java.awt.*;
      import java.awt.event.*;

      public class Arith extends Frame implements ActionListener
      {
      // reference variables
      TextField tf1, tf2, tf3; // 3 text fields
      Button pb, mb1, mb2, mb3, db, eb; // 6 buttons

      public Arith( )
      {
      // setting the layout
      setLayout(new GridLayout(6, 2, 5, 5));
      setBackground(Color.cyan);

      // creating objects
      tf1 = new TextField(10);
      tf2 = new TextField(10);
      tf3 = new TextField(10);

      pb = new Button(“+”);
      mb1 = new Button(“-“);
      mb2 = new Button(“*”);
      mb3 = new Button(“%”);
      db = new Button(“/”);
      eb = new Button(“EXIT”);

      // event handling
      pb.addActionListener(this);
      mb1.addActionListener(this);
      mb2.addActionListener(this);
      mb3.addActionListener(this);
      db.addActionListener(this);
      eb.addActionListener(this);

      // beautification
      eb.setForeground(Color.red);
      tf3.setEditable(false);
      tf3.setFont(new Font(“Serif”, Font.BOLD,20));

      // adding components, order is important
      add(new Label(“Enter 1st Number”));
      add(tf1);

      add(new Label(“Enter 2nd Number”));
      add(tf2);

      add(pb); // adding buttons one by one
      add(mb1);
      add(mb2);
      add(mb3);
      add(db);
      add(eb);

      add(new Label(“Result”)); // adding last row
      add(tf3);
      // create the frame
      setTitle(“Arithmetic”);
      setSize(400,450);
      setVisible(true);
      }
      // override the abstract method of AL
      public void actionPerformed(ActionEvent e)
      {
      String s1 = tf1.getText();
      double d1 = Double.parseDouble(s1);
      double d2 = Double.parseDouble(tf2.getText());

      // Object obj = e.getSource();
      // Button btn = (Button) obj;
      Button btn = (Button) e.getSource();

      // getSource( ) returns the object of the button (in Object form).

      String s2 = ” “; // a temporary local variable

      if(btn == pb)
      s2 = “sum = ” + (d1+d2);
      // assign a value to s2
      else if(btn == mb1)
      s2 = “Difference = ” + Math.abs(d1-d2);
      else if(btn == mb2)
      s2 = “Product = ” + (d1*d2);
      else if(btn == mb3)
      s2 = “Remainder = “+ (d1%d2);
      else if(btn == db)
      s2 = “Quotient = ” + Math.round((d1/d2));
      else if(btn == eb)
      {
      System.exit(0); // closes the current application
      }

      tf3.setText(s2); // place the result s2 in tf3
      }
      public static void main(String[] args)
      {
      new Arith();
      }
      }

    1. import java.awt.*;
      import java.awt.event.*;

      public class Demo extends Frame implements ActionListener
      {
      List selectList, displayList;
      public Demo()
      {
      setLayout(new GridLayout(2, 2, 10, 15));

      selectList = new List(5, true);
      displayList = new List(5, true);

      selectList.add(“S N Rao”);
      selectList.add(“way2java.com”);
      selectList.add(“Hyderabad”);
      selectList.add(“Andhra Pradesh”);
      selectList.add(“India”);

      selectList.addActionListener(this);

      add(new Label(“Enter Here”)); add(selectList);
      add(new Label(“Display Here”)); add(displayList);

      setSize(300, 350);
      setVisible(true);
      }
      public void actionPerformed(ActionEvent e)
      {
      String names[] = selectList.getSelectedItems();
      displayList.removeAll();
      for(int i = 0; i < names.length; i++) { displayList.add(names[i]); } } public static void main(String args[]) { new Demo(); } }

    1. The code should be below
      import java.awt.*;
      import java.awt.event.*;
      public class SumDemo extends Frame implements ActionListener
      {
      Button sum,reset;
      Label l1,l2,l3;
      TextField t1,t2,t3;
      public SumDemo()
      {
      setTitle(“Button Example”);
      setSize(400,200);
      setVisible(true);
      addWindowListener(new WindowAdapter()
      {
      public void windowClosing(WindowEvent e)
      {
      System.exit(0);
      }
      });
      setLayout(new GridLayout(4,2,20,20));

      sum = new Button(“Add”);
      reset = new Button(“Reset”);
      l1 = new Label(“Enter the 1st number”);
      l2 = new Label(“Enter the 2nd number”);
      l3 = new Label(“Result”);
      t1 = new TextField(10);
      t2 = new TextField(10);
      t3 = new TextField(10);

      setBackground(Color.pink);
      t1.setBackground(new Color(200,200,200));
      t2.setBackground(new Color(200,200,200));
      t3.setBackground(new Color(200,200,200));
      t3.setEditable(false);

      sum.addActionListener(this);
      reset.addActionListener(this);

      add(l1);
      add(t1);
      add(l2);
      add(t2);
      add(l3);
      add(t3);
      add(sum);
      add(reset);
      }
      public void actionPerformed(ActionEvent e)
      {
      String str = e.getActionCommand();
      if(str.equals(“Add”))
      {
      String s1 = t1.getText();
      String s2 = t2.getText();
      int n1 = Integer.parseInt(s1);
      int n2 = Integer.parseInt(s2);
      int n = n1 + n2;
      String s = String.valueOf(n);
      t3.setText(s);
      }
      else if(str.equals(“Reset”))
      {
      t1.setText(“”);
      t2.setText(“”);
      t3.setText(“”);
      }
      }
      public static void main(String args[])
      {
      new SumDemo();
      }
      }

  4. Excellent code..
    but still have a query???
    Hoe to put validations on the text feild,suppose if i enter string in the textfeild it should give error.but its not.plz reply

    1. Question must be more clear. I give some options.

      a) Suppose your enter a wrong character, like a special character or a digit which the password does not accept, it must give error immediately (not waiting for whole word). The easiest way is to use a dialog box here from Swing.

      b) Entering all the characters and then validate. etc, etc.

      SN Rao

Leave a Comment

Your email address will not be published.