Write a Java Program to generate a simple calculator Using JAVA Swing.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import javax.swing.*;
/*
<applet code="JSwing_xyz"
width=200 height=300>
</applet>
*/
public class JSwing_xyz extends JApplet
implements ActionListener
{
Double
cv=0.0,pv=0.0,result=0.0;
int
count=0;
JTextField
opd1 = new JTextField(10);
JTextField opd2 = new JTextField(10);
JTextField oprt = new JTextField(1);
JTextField
Res = new JTextField(10);
String
opr="";
public
void init()
{
int
i=0;
JButton b[] = new JButton[17];
String
a[] =
{"0","1","2","3","4","5","6","7","8","9",".","+","-","*","/","=","Clear"};
setLayout(new
GridLayout(0,4));
add(new
JLabel("Operand 1: "));
add(opd1);
add(new JLabel("Operator:
"));
add(oprt);
add(new
JLabel("Operand 2: "));
add(opd2);
add(new
JLabel("Result: "));
add(Res);
opd1.addActionListener(this);
opd2.addActionListener(this);
oprt.addActionListener(this);
Res.addActionListener(this);
//setLayout(new
GridLayout(0,3));
for(i=0;i<17;i++)
{
b[i]
= new JButton(a[i]);
add(b[i]);
b[i].addActionListener(this);
}
opd1.setText("");
}
public
void actionPerformed(ActionEvent ae)
{
String s=ae.getActionCommand();
if(s.equals("+")
|| s.equals("-") || s.equals("/") ||
s.equals("*"))
{ count++;
oprt.setText(s);
opd2.setText("");
opr=s;
pv
= Double.parseDouble(opd1.getText());
}
else
if(s.equals("="))
{
cv=Double.parseDouble(opd2.getText());
if(opr
== "+")
result
= pv+cv;
else
if(opr == "-")
result
= pv-cv;
else
if(opr == "*")
result
= pv*cv;
else
if(opr == "/")
result
= pv/cv;
}
else
if(s.equals("Clear"))
{
pv=cv=result=0.0;
count=0;
opd1.setText("0");
opd2.setText("0");
//oprt.setText("0");
}
else
{
if(count==0)
opd1.setText(opd1.getText().concat(s));
else
opd2.setText(opd2.getText().concat(s));
}
Res.setText(String.valueOf(result));
}
}
Output:
Comments
Post a Comment