Java Graphics Programming Exercise
Problem Statement-1:
Write a java program to perform calculations like addition, subtraction, multiplication, and division using AWT and applets. Create three Text Fields for entering a first number, the second number, and displaying the result. Add four buttons for performing addition, subtraction, multiplication, and division.
Test Data:
Perform Multiplication
First Number : 12
Second Number : 23
Expected output:
First Number : 12
Second Number : 23
Result : 276
Solution:
//Calculator.java
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class Calculator extends Applet implements ActionListener{
String msg="";
TextField t1, t2, t3;
Button b1,b2,b3,b4;
Label l1,l2,l3;
public void init(){
l1 = new Label("\\n First Number");
add(l1);
t1 = new TextField(15);
add(t1);
l2 = new Label("\\n Second Number");
add(l2);
t2 = new TextField(15);
add(t2);
l3 = new Label("\\n Result");
add(l3);
t3 = new TextField(15);
add(t3);
b1 = new Button("\\n ADD");
add(b1);
b1.addActionListener(this);
b2 = new Button("\\n SUB");
add(b2);
b2.addActionListener(this);
b3 = new Button("\\n MUL");
add(b3);
b3.addActionListener(this);
b4 = new Button("\\n DIV");
add(b4);
b4.addActionListener(this);
}
public void actionPerformed(ActionEvent e){
if(e.getSource()==b1){
int x = Integer.parseInt(t1.getText());
int y = Integer.parseInt(t2.getText());
int sum = x+y;
t3.setText(" "+sum);}
if(e.getSource()==b2){
int x = Integer.parseInt(t1.getText());
int y = Integer.parseInt(t2.getText());
int sub = x-y;
t3.setText(" "+sub);}
if(e.getSource()==b3){
int x = Integer.parseInt(t1.getText());
int y = Integer.parseInt(t2.getText());
int mul = x*y;
t3.setText(" "+mul);}
if(e.getSource()==b4){
int x = Integer.parseInt(t1.getText());
int y = Integer.parseInt(t2.getText());
int div = x/y;
t3.setText(" "+div);}
showStatus("\\nCalculator Project");
repaint();
}
}
//Calculator.html
<html>
<head>
<applet code=Calculator.class
width=150
height=150>
</applet>
</head>
</html>
Output:

Explanation:
The class Calculator extends Applet implements ActionListener contains t1, t2, t3 in Text Field type and b1, b2, b3, b4 in Button type. The Label l1, l2, l3 are used to display the labels. Using t1.getText() and t2.getText() the values from text field is fetch to perform calculation.