//Program to create a calculator using eventhandling.
//Solution:
import javsa.awt.*;
import java.awt.event.*;
import java.applet.Applet;
/*
<applet code=”calculator” width=200 height=150>
</applet>
*/
public class calculator extends Applet implements ActionListener
{
Label label1,label2;
TextField text1,text2,text3;
Button add1,sub,prod,div;
public void init()
{
label1=new Label(“Enter A”);
add(label1);
label2=new Label(“Enter B”);
add(label2);
text1=new TextField(10);
add(text1);
text2=new TextField(10);
add(text2);
add1=new Button(“+”);
add(add1);
add1.addActionListener(this);
sub=new Button(“-”);
add(sub);
sub.addActionListener(this);
prod=new Button(“*”);
add(prod);
prod.addActionListener(this);
div=new Button(“/”);
text3=new TextField(10);
add(text3);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==add1)
{
int a=Integer.parseInt(text1.getText());
int b=Integer.parseInt(text2.getText());
int sum=a+b;
text3.setText(String.valueOf(sum));
}
if(e.getSource()==sub)
{
int a=Integer.parseInt(text1.getText());
int b=Integer.parseInt(text2.getText());
int diff=a-b;
text3.setText(String.valueOf(diff));
}
if(e.getSource()==prod)
if(e.getSource()==prod)
{
int a=Integer.parseInt(text1.getText());
int b=Integer.parseInt(text2.getText());
int pro=a*b;
text3.setText(String.valueOf(pro));
}
if(e.getSource()==div)
{
int a=Integer.parseInt(text1.getText());
int b=Integer.parseInt(text2.getText());
int div=a/b;
text3.setText(String.valueOf(div));
}
}
}
|
|

To create a calculator using event handling.
|
|
| |
|
|
|
|