package Works_JavaLesson;
import java.awt.*;
import java.awt.event.*;
public class SimpleCalculator {
/**
* @param simple calculator
* @author CHENJIAN
*/
public static void main(String[] args) {
SimpleCalculatorFrame frame = new SimpleCalculatorFrame();
frame.setVisible(true);
frame.addWindowListener(
new WindowAdapter(){
public void windowClosing(WindowEvent event){
System.exit(0);
}
});
}
}
class SimpleCalculatorFrame extends Frame{
public SimpleCalculatorFrame(){
setTitle("--- Simple Calculator ---");
setLocation(300, 200);
setLayout(new BorderLayout());
SimpleCalculatorPanel panel = new SimpleCalculatorPanel();
add(panel);
pack();
}
}
class SimpleCalculatorPanel extends Panel{
public SimpleCalculatorPanel(){
setLayout(new BorderLayout());
panel_A = new Panel();
panel_B = new Panel();
lastCommand = "=";
result = 0;
textfield = new TextField(30);
textfield.setBackground(Color.WHITE);
panel_A.add(textfield, BorderLayout.NORTH);
add(panel_A);
panel_B.setLayout(new GridLayout(2, 3, 3, 3));
ActionListener command = new CommandAction();
makeButton("*", command);
makeButton("-", command);
makeButton("%", command);
makeButton("+", command);
makeButton("/", command);
makeButton("=", command);
add(panel_B, BorderLayout.SOUTH);
}
public void makeButton(String name, ActionListener listener){
Button btn = new Button(name);
btn.addActionListener(listener);
panel_B.add(btn);
}
private class CommandAction implements ActionListener{
public void actionPerformed(ActionEvent event){
String input = event.getActionCommand();
if(lastCommand.equals("=")){
result = Double.parseDouble(textfield.getText());
}
else if(lastCommand.equals("*")){
result *= Double.parseDouble(textfield.getText());
}
else if(lastCommand.equals("/")){
result /= Double.parseDouble(textfield.getText());
}
else if(lastCommand.equals("+")){
result += Double.parseDouble(textfield.getText());
}
else if(lastCommand.equals("-")){
result -= Double.parseDouble(textfield.getText());
}
else if(lastCommand.equals("%")){
result %= Double.parseDouble(textfield.getText());
}
lastCommand = input;
textfield.setText(String.valueOf(result));
}
}
private Panel panel_A;
private Panel panel_B;
private double result;
private String lastCommand;
private TextField textfield;
}
2009-05-28 09:51:22