// Swing components
// calculator
// event driven programming
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class calculator implements ActionListener
{
double
n1, n2, result;
JButton
b1, b2, b3, b4, b5, b6, b7, b8, b9, b0;
JButton
add,sub,mul,div,eq,dot;
JTextField
tf;
JFrame
jf;
JPanel
p1, p2;
String
s1="";
double
Num1=0;
double
Num2=0;
double
res=0;
String
opn="";
calculator()
{
jf
= new JFrame();
jf.setSize(250,200);
jf.setTitle("Calculator");
tf
= new JTextField("0");
tf.setEditable(false);
tf.setHorizontalAlignment(JTextField.RIGHT);
jf.add(tf,
BorderLayout.NORTH);
GridLayout
GL = new GridLayout(4,4);
p2
= new JPanel();
p2.setLayout(GL);
b1
= new JButton("1");
b2
= new JButton("2");
b3
= new JButton("3");
b4
= new JButton("4");
b5
= new JButton("5");
b6
= new JButton("6");
b7
= new JButton("7");
b8
= new JButton("8");
b9
= new JButton("9");
b0
= new JButton("0");
add
= new JButton("+");
sub
= new JButton("-");
mul
= new JButton("*");
div
= new JButton("/");
eq
= new JButton("=");
dot
= new JButton(".");
p2.add(b9);
p2.add(b8);
p2.add(b7);
p2.add(div);
p2.add(b6);
p2.add(b5);
p2.add(b4);
p2.add(mul);
p2.add(b3);
p2.add(b2);
p2.add(b1);
p2.add(sub);
p2.add(b0);
p2.add(dot);
p2.add(eq);
p2.add(add);
jf.add(p2,
BorderLayout.CENTER);
b0.addActionListener(this);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
b5.addActionListener(this);
b6.addActionListener(this);
b7.addActionListener(this);
b8.addActionListener(this);
b9.addActionListener(this);
add.addActionListener(this);
sub.addActionListener(this);
mul.addActionListener(this);
div.addActionListener(this);
eq.addActionListener(this);
dot.addActionListener(this);
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public
void actionPerformed(ActionEvent ae)
{
String
str = ae.getActionCommand();
if((str.equals("+"))||(str.equals("-"))||(str.equals("*"))||(str.equals("/")))
{
Num1
= Double.parseDouble(s1);
s1="";
tf.setText("");
opn=str;
}
else
if(str.equals("="))
{
Num2
= Double.parseDouble(s1);
s1="";
char
op = opn.charAt(0);
switch(op)
{
case
'+': res = Num1+Num2;
break;
case
'-': res = Num1-Num2;
break;
case
'*': res = Num1*Num2;
break;
case
'/': res = Num1/Num2;
break;
}
tf.setText(String.valueOf(res));
}
else
{
s1=s1+str;
tf.setText(s1);
}
}
public
static void main(String as[])
{
new
calculator();
}
}
No comments:
Post a Comment
Don't be a silent reader...
Leave your comments...
Anu