java applet

Hello guys today I am gonna show how to add 2 numbers using Java Applet.

Since we are using Applet, the first thing we should do is extend the Applet class.

public class sum_of_numbers extends Applet implements ActionListener

Here we extend the Applet class and then we implement the ActionListener interface. We need ActionListener because it provides us the methods to interact with buttons to find the sum of the numbers. After that we declare our variables :

  • 2 textfields to hold the numbers
  • 2 buttons, 1 to get the sum and the other one to reset the fields
  • 3 labels : label_1 for telling the user to input the first number, label_2 for telling the user to input the first number and label_3 for displaying the sum
private TextField text1 , text2;
private Button sum,reset;
private Label label1, label2 , label3;

The next step is to construct our declared variables one by one.

label1 = new Label("Input First Number : ");
add(label1);
text1 = new TextField(10);
text1.setText("0");
add(text1);
label2 = new Label("Input Second Number : ");
add(label2);

text2 = new TextField(10);
text2.setText("0");
add(text2);

sum = new Button("Sum");
sum.addActionListener(this);
add(sum);

reset = new Button("Reset Values");
reset.addActionListener(this);
add(reset);

label3 = new Label("Sum is : ");
add(label3);

setSize(800,200);

You can see in the last line that we also set the size of our Applet where 800 is the width and 200 is the height.

So now we have our variables. All we need to do is to call the actionPerformed method of the ActionListener interface and we are good to go.

In this method we need to tell the program what to do if the sum button or reset button is clicked.

  1. sum button is clicked

Since we input the numbers in a textfield, we need to cast them and get their Integer value. Afterwards we add the number and display their sum.

2. reset button is clicked

Here we reset the textfield values so that the user can input them again. We also reset the value of the label which displays us the sum.

 

public void actionPerformed(ActionEvent e) 
	{
		if(e.getSource() == sum)
		{
			int nr1 = Integer.parseInt(text1.getText());
			int nr2 = Integer.parseInt(text2.getText());
			
			int sum1 = nr1 + nr2;
			label3.setText(Integer.toString(sum1));
		}
		
		else if(e.getSource() == reset)
		{
			text1.setText(" ");
			text2.setText(" ");
			label3.setText(" ");
		}
	}

The full code : https://bittlife.com/tutorial_files/sum_of_numbers.java

That is all. Please don’t forget to like and subscribe and most importantly if you have any questions feel free to leave a comment below.

 

LEAVE A REPLY

Please enter your comment!
Please enter your name here