Monday, 10 March 2014

Calculator program without using ActionListener

/*
<applet code="Calculator.class" height =200 width=200>
</applet>
*/

import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class Calculator extends Applet
{
String first,op;
TextField t1;
Button b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,b12,b13,b15,b14,b0;
public void init()
{
t1=new TextField(40);
b0=new Button("0");
b1=new Button("1");
b2=new Button("2");
b3=new Button("3");
b4=new Button("4");
b5=new Button("5");
b6=new Button("6");
b7=new Button("7");
b8=new Button("8");
b9=new Button("9");
b10=new Button("+");
b11=new Button("-");
b12=new Button("*");
b13=new Button("/");
b14=new Button(".");
b15=new Button("=");
Panel p=new Panel();

p.setLayout(new GridLayout(4,4));


p.add(b0); p.add(b1);
p.add(b2); p.add(b3);
p.add(b4); p.add(b5);
p.add(b6); p.add(b7);
p.add(b8); p.add(b9);
p.add(b10); p.add(b11);
p.add(b12); p.add(b13);
p.add(b14); p.add(b15);

Panel p1=new Panel();
p1.setLayout(new BorderLayout());
p1.add("North",t1);
p1.add("Center",p);
add(p1);
}
public boolean action(Event e,Object o)
{
if(o.equals("0"))
t1.setText(t1.getText()+"0");
if(o.equals("1"))
t1.setText(t1.getText()+"1");
if(o.equals("2"))
t1.setText(t1.getText()+"2");
if(o.equals("3"))
t1.setText(t1.getText()+"3");
if(o.equals("4"))
t1.setText(t1.getText()+"4");
if(o.equals("5"))
t1.setText(t1.getText()+"5");
if(o.equals("6"))
t1.setText(t1.getText()+"6");
if(o.equals("7"))
t1.setText(t1.getText()+"7");
if(o.equals("8"))
t1.setText(t1.getText()+"8");
if(o.equals("9"))
t1.setText(t1.getText()+"9");
if(o.equals("."))
t1.setText(t1.getText()+".");
if(o.equals("+"))
{
first=t1.getText();
op="+";
t1.setText("");
}
if(o.equals("-"))
{
first=t1.getText();
op="-";
t1.setText("");
}
if(o.equals("*"))
{
first=t1.getText();
op="*";
t1.setText("");
}
if(o.equals("/"))
{
first=t1.getText();
op="/";
t1.setText("");
}
if(o.equals("="))
{
float x=Float.parseFloat(first);
float y=Float.parseFloat(t1.getText());
float z=0.0f;
if(op.equals("+"))
{
z=x+y;
}
if(op.equals("-"))
{
z=x-y;
}
if(op.equals("*"))
{
z=x*y;
}
if(op.equals("/"))
{
z=x/y;
}
t1.setText(""+z);
}
return true;
}
}

2 comments: