chenshuai123
发贴: 2
积分: 0
|
于 2007-11-05 00:17
我是新手,才学半个月.这是我写的,大家给点意见,谢谢大家,共同提高: import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class Computer implements ActionListener{ private TextField tf = new TextField("0",30); private Button[] b = new Button[20]; private String[] label = {"back","CE","C","+","7", "8","9","-","4","5","6","*","1","2","3","/","0", "+/-",".","="}; private boolean flag = false; private double d1 = 0; private double d2 = 1; private String operator = "+"; public Computer(){ Frame f = new Frame("Computer"); f.add(tf,"North"); Panel p = new Panel(); MenuBar mb = new MenuBar(); Menu m1 = new Menu("编辑"); Menu m2 = new Menu("帮助"); MenuItem mi1 = new MenuItem("复制"); MenuItem mi2 = new MenuItem("粘贴"); MenuItem mi3 = new MenuItem("关于计算器"); m1.add(mi1); m1.add(mi2); m2.add(mi3); mb.add(m1); mb.add(m2); f.setMenuBar(mb); p.setLayout(new GridLayout(5,4,5,5)); for(int i=0;i<b.length;i++){ b[i] = new Button(label[i]); p.add(b[i]); b[i].addActionListener(this); } f.add; tf.setEditable(false); f.setVisible(true); f.setResizable(false); f.pack(); } public static void main(String[] args) { new Computer(); } public void actionPerformed(ActionEvent ae) { String command = ae.getActionCommand(); if(command.equals("0")||command.equals("1")|| command.equals("2")||command.equals("3")|| command.equals("4")||command.equals("5")|| command.equals("6")||command.equals("7")|| command.equals("8")||command.equals("9")){ if(flag){ tf.setText(tf.getText()+command); }else{ tf.setText(command); flag = true; } }else if(command.equals(".")){ String temp = tf.getText(); if(temp.indexOf(".")==-1){ tf.setText(temp+"."); flag=true; } }else if(command.equals("+")||command.equals("-")|| command.equals("*")||command.equals("/")){ d1 = Double.parseDouble(tf.getText()); operator = command; flag = false; }else if(command.equals("=")){ d2 = Double.parseDouble(tf.getText()); if(operator.equals("+")){ d1 = d1+d2; }else if(operator.equals("-")){ d1 = d1-d2; }else if(operator.equals("*")){ d1 = d1*d2; }else if(operator.equals("/")){ d1 = d1/d2; } tf.setText(""+d1); flag = false; } }
}
|