package aa;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Calculator1 extends JFrame implements ActionListener {
private JTextField m_textField = new JTextField(12);
private JButton[] m_button = { new JButton("1"), new JButton("2"),
new JButton("3"), new JButton("4"), new JButton("5"),
new JButton("6"), new JButton("7"), new JButton("8"),
new JButton("9"), new JButton("0"), new JButton("+"),
new JButton("-"), new JButton("*"), new JButton("/"),
new JButton("."), new JButton("="), new JButton("C") };
public Calculator1() {
super("Calculator");
Container container = getContentPane();
container.setLayout(new FlowLayout(FlowLayout.CENTER));
container.add(m_textField);
for (int i = 0; i <= 16; i++) {
container.add(m_button[i]);
m_button[i].addActionListener(this);
}
setSize(200, 200);
setVisible(true);
}
int flag;
double value1, value2, result;//
public void actionPerformed(ActionEvent e) {
int i;
for (i = 0; i < 10; i++) {
if (e.getSource() == m_button[i]) {
String value = String.valueOf((i + 1) % 10);
m_textField.setText(m_textField.getText() + value);
}
}
if (e.getSource() == m_button[10]) //
{
flag = 1;
value1 = Double.parseDouble(m_textField.getText());//
m_textField.setText(""); //
} else if (e.getSource() == m_button[11]) //
{
flag = 2;
value1 = Double.parseDouble(m_textField.getText());
m_textField.setText("");
} else if (e.getSource() == m_button[12])//
{
flag = 3;
value1 = Double.parseDouble(m_textField.getText());
m_textField.setText("");
} else if (e.getSource() == m_button[13]) //
{
flag = 4;
value1 = Double.parseDouble(m_textField.getText());
m_textField.setText("");
} else if (e.getSource() == m_button[15]) // =
{
value2 = Double.parseDouble(m_textField.getText()); //
if (flag == 1)
result = value1 + value2;
else if (flag == 2)
result = value1 - value2;
else if (flag == 3)
result = value1 * value2;
else if (flag == 4) {
if (value2 != 0)
result = value1 / value2;
else
result = 0;
}
String r = String.valueOf(result);
m_textField.setText(r);
} else if (e.getSource() == m_button[14]) // .
{
boolean b = true;// whether exists '.'
String r = m_textField.getText();//
for (int j = 0; j < r.length(); j++) {
if (r.charAt(j) == ".".charAt(0)){
b = false;
}
}
if (b){
m_textField.setText(m_textField.getText() + ".");
}
} else if (e.getSource() == m_button[16]) //
m_textField.setText("");
}
public static void main(String args[]) {
Calculator1 app = new Calculator1();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}