import java.awt.Frame;
import java.awt.TextField;
import java.awt.Button;
import java.awt.Panel;
import java.awt.GridLayout;
import java.awt.Panel;
import java.awt.Color;
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
import java.awt.event.WindowListener;
import java.awt.event.WindowEvent;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Calculator extends Frame implements WindowListener, ActionListener{
TextField result;
Button[] button;
boolean num_state = true;
boolean operator_state=true;
String op_temp;
String num_temp;
public void init() {
result = new TextField("0", 30);
result.setEditable(false);
String[] buttonTitle = {"7", "8", "9", "/",
"4", "5", "6", "*",
"1", "2", "3", "-",
"C", "0", "=", "+"};
button = new Button[16];
Panel p = new Panel();
p.setLayout(new GridLayout(4,4,3,3));
for (int i=0; i<button.length; i++ ) {
button[i] = new Button(buttonTitle[i]);
button[i].setBackground(new Color(58, 226, 206));
p.add(button[i]);
button[i].addActionListener(this);
} //for
this.add("North", result);
this.add("Center", p);
this.setTitle("Calculator");
this.setBounds(600,300,200,200);
this.setVisible(true);
this.addWindowListener(this);
}//init()
public void windowActivated(WindowEvent e) { }
public void windowClosed(WindowEvent e) { }
public void windowClosing(WindowEvent e) {
System.exit(0);
}
public void windowDeactivated(WindowEvent e) { }
public void windowDeiconified(WindowEvent e) { }
public void windowIconified(WindowEvent e) { }
public void windowOpened(WindowEvent e) { }
public void actionPerformed(ActionEvent e) {
String in = e.getActionCommand();
if(in.equals("C")){
result.setText("0");
num_state = true;
}else if('0' <= in.charAt(0) && in.charAt(0) <= '9') {
if (num_state)
result.setText(in);
else
result.setText(result.getText() +in);
num_state = false;
}
if(in.equals("/") || in.equals("*") || in.equals("-") || in.equals("+")) {
num_temp = result.getText();
op_temp = in;
num_state=true;
}else if(in.equals("=")) {
if(operator_state) {
double num1 = Double.parseDouble(num_temp);
double num2 = Double.parseDouble(result.getText());
if(op_temp.equals("+")) {
result.setText("" + (num1+num2));
}else if(op_temp.equals("-")) {
result.setText("" + (num1-num2));
}else if(op_temp.equals("*")) {
result.setText("" + (num1*num2));
}else if(op_temp.equals("/")) {
result.setText("" + (num1/num2));
}
}
}
}
public static void main(String[] args) {
Calculator ct = new Calculator();
ct.init();
}
}
YASU.exe
