An Applet Program to Add Two Numbers

Applets are simple Java programs that run in web browsers. The creation of web pages is related to Java Applet. An applet is an Internet-based Java program that can be included in an HTML page. An applet is a Java class defined in JDK’s java. applet package.

Addition of Two Numbers using Applet

import java.awt.*;

import java.applet.*;

import java.awt.event.*;

public class additionn extends Applet implements ActionListener

/*class with the appropriate listener interface*/

{

Label lno1,lno2,lresult;

TextField tno1,tno2,tresult;

Button badd,bclear;

public void init()

{

lno1=new Label(“enter no”);

lno2=new Label(“enter no”);

lresult=new Label(“Result”);

tno1=new TextField(20);

tno2=new TextField(20);

tresult=new TextField(20);

badd=new Button(“add”);

bclear=new Button(“clear”);

add(lno1);add(tno1);

add(lno2);add(tno2);

add(lresult);add(tresult);

add(badd);add(bclear);

//register the component(button) with the listener

badd.addActionListener(this);                                  

bclear.addActionListener(this);

}

public void actionPerformed(ActionEvent aee)   

//action performed on badd, bclear    

{

if(aee.getSource()==badd)         

//action performed on badd button

{

int no1,no2,result;

no1=Integer.parseInt(tno1.getText());

no2=Integer.parseInt(tno2.getText());

result=no1+no2; //calculation

tresult.setText(String.valueOf(result));

}

//code for clear all the textfields

if(aee.getSource()==bclear)

{

tno1.setText(” “);

tno2.setText(” “);

tresult.setText(” “);

}

}

}

//<applet code=”additionn.class” height=500 width=500></applet>

Program to Add Two Numbers In Applet

Explanation.

Init()-when a document with an applet is opened, the init() method is automatically called to initialize the applet. We do not need to explicitly call this method.

In above example we use three labels(lno1,lno2,lresult) and three textfields(tno1, tno2,tresult) and two buttons(badd, bclear).

We can add integers(or any number) in the text field same as a calculator.

Put numbers in the text field tno1 and tno2 and then Press the badd button  and  the output will be displayed in the text field(tresult). Bclear button is used to refresh all the textfields(tno1, tno2, treault).