Java Applet Program to Add Two Numbers Taking Values from the User
File:- JavaApplication.java
import java.applet.*;
import java.awt.event.*;
/* <applet code="javaapplication.class" width="400" height="300"></applet> */
public class JavaApplication extends Applet implements ActionListener
{
Button b; //for add button
TextField t1; //to take number inputs
TextField t2;
Label l; //to display result
int x,y,z; //for calculation
public void init() //applet's init() method
{
t1=new TextField(); //allocating memory to the objects
t2=new TextField();
b=new Button("ADD"); //button text is ADD
add(t1);
add(b); //then dding button into applet window
l=new Label("Answer is:"); //default text of the label
add(l); //adding the label into applet window
b.addActionListener(this); //adding event action to the button
}
public void paint(Graphics g) //applet's paint method
{
g.drawString("Enter two numbers",10,20); //prompting the user to input two numbers
}
@Override
public void actionPerformed(ActionEvent e) //actionPerformed method for the calculation
{
if(e.getSource() == b) //if the button b is pressed
{
x = Integer.parseInt(t1.getText()); //initializing x with the value of t1 textfield
y = Integer.parseInt(t2.getText()); //initializing y with the value of t2 textfield
z = x+y; // initializing z with addition of x & y
l.setText(String.valueOf(z)); //setting the text of label l with the value z
}
}
}
Output:-
Here we have to import the awt, applet & event packages for this program. Our JavaApplication class must inherit the Applet class to create an applet window and also must implement the ActionListener interface to perform a button click event.
The click event is managed in the void actionPerformed method where we have to use the object e of ActionEvent class. If button b is pressed then it will create an action, so we have to check the source of the ActionEvent object e is equal to button b or not.
The user inputs integer values into the t1 & t2 boxes. Then we have to store the values of the t1 & t2 text fields into the variables x & y. The addition result of x+y is stored in the variable z. The value of z is then set into the label l, it will append the text Answer is: followed by the result.
And other explanations are given in the form of comments on each line of code. Just copy the code, execute and see the applet as it is showing in the output section. Don't forget to give comments on your valuable queries.
0 Comments