You are on page 1of 5

PROGRAM TO MAKE A CALCULATOR USING FRAME

import java.awt.event.*; import java.awt.*; public class calci extends Frame implements ActionListener{ TextField t; Button btn[]=new Button[10]; Button add,mul,div,sub,eq,clr,clr1; long a= Long.MAX_VALUE,b=Long.MAX_VALUE,r; String op="",s="",ac=""; boolean f=false,f1=false; public calci() { setLayout(new BorderLayout(0,4)); GridLayout g=new GridLayout(4,5,4,4); t=new TextField(30); add(t,BorderLayout.NORTH); Panel p=new Panel(); p.setLayout(g); for(int i=9;i>0;i--) { btn[i]=new Button(""+i); p.add(btn[i]); btn[i].addActionListener(this); } btn[0]=new Button("0"); btn[0].addActionListener(this); add=new Button("+"); sub=new Button("-"); div=new Button("/"); mul=new Button("*"); eq=new Button("="); clr=new Button("clr"); clr1=new Button("allclr");

p.add(add,3); p.add(sub,7); p.add(mul,11); p.add(clr,12); p.add(btn[0],13); p.add(eq,14); p.add(div,15); add(clr1,BorderLayout.SOUTH); add(p,BorderLayout.CENTER); add.addActionListener(this); sub.addActionListener(this); div.addActionListener(this); mul.addActionListener(this); eq.addActionListener(this); clr.addActionListener(this); t.addActionListener(this); clr1.addActionListener(this); t.setEditable(false); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent w) { System.exit(0); } });

public void cal() //calculate funcn { if(a== Long.MAX_VALUE ||b== Long.MAX_VALUE) //checking invalid input { s=" Wrong Expression ";r=-1;} else { if(op=="+") //add r=a+b; else if(op=="-") //sub r=a-b; else if(op=="/") //div r=a/b;

else r=a*b; //multiply s=""+r; //initialising string to result a=Long.MAX_VALUE;b= Long.MAX_VALUE; //clearing inputs

} public void actionPerformed(ActionEvent e) { ac=e.getActionCommand(); if(ac=="+"||ac=="-"||ac=="/"||ac=="*") //if any operator pressed { if(f1) //if op pressed after an = { f1=false; s=""; t.setText(s); op=ac; } else if(f) //op pressed after an op { if(s=="") { //obtaining second operand b=-1; } else b=Long.parseLong(s); cal(); a=r; t.setText(s); //displaying results s=""; op=ac; } else { op=ac; f=true; //setting flag if consecutive operand key pressed if(s=="") a= Long.MAX_VALUE; //obtaining first operand else a=Long.parseLong(s);

t.setText(""); //clearing text field s=""; } else if("=".equals(ac)) { f=false; f1=true; //setting flag that an = is pressed if(s=="") //obtaining second operand b= Long.MAX_VALUE; else b=Long.parseLong(s); cal(); a=r; t.setText(s); //displaying result s=""; } else if("allclr".equals(ac)) //clearing everything { s=""; t.setText(s); f=false;f1=false; } else if(ac=="clr") //clearing current value { if(f1) a= Long.MAX_VALUE; s=""; t.setText(s); } else //inputting nos { f1=false; s=s+ac; t.setText(s); } repaint(); }

} public static void main(String arg[]) { calci c=new calci();

} }

c.setVisible(true); c.setSize(200, 250); c.setResizable(false);

You might also like