dickran
发贴: 4
积分: 0
|
于 2006-05-28 11:52
package jsq;
import java.awt.*; import java.awt.event.*; import java.applet.*; /** * <p>Title: </p> * <p>Description: </p> * <p>Copyright: Copyright 2006</p> * <p>Company: </p> * @author unascribed * @version 1.0 */
public class Frame1 extends Frame implements ActionListener { TextField t=new TextField("",15); Panel p1=new Panel(); Button[] b=new Button[10]; Button bAdd=new Button("+"); Button bSub=new Button("-"); Button bMul=new Button("*"); Button bDiv=new Button("/"); Button bPoint=new Button("."); Button bEqual=new Button("="); Button bNull=new Button("清空"); String str1=""; String str2=""; String operator=null; boolean first=true; int countOper=0; double result=0.0; double num1=0.0,num2=0.0; boolean error=false;
public Frame1() { t.setEditable(false); for(int i=0;i<b.length;i++) { b[i]=new Button(String.valueOf); p1.add(b[i]); b[i].setActionCommand("number"); b[i].addActionListener(this); } p1.add(bPoint); bPoint.setActionCommand("number"); p1.add(bAdd); p1.add(bSub); p1.add(bMul); p1.add(bDiv); p1.add(bEqual); p1.add(bNull); bAdd.setActionCommand("oper"); bSub.setActionCommand("oper"); bMul.setActionCommand("oper"); bDiv.setActionCommand("oper"); bAdd.addActionListener(this); bSub.addActionListener(this); bMul.addActionListener(this); bDiv.addActionListener(this); bPoint.addActionListener(this); bEqual.addActionListener(this); bNull.addActionListener(this); p1.setLayout(new GridLayout(4,4,5,5)); add(t,"North"); add(p1,"Center"); setLocation(400,200); setSize(200,200); setBackground(Color.lightGray); setVisible(true);
addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e) { System.exit(0); } }); }
public void actionPerformed(ActionEvent e) { Button temp=(Button)e.getSource(); if(e.getActionCommand().equals("number")) { if(first) { str1=str1+temp.getLabel(); t.setText(str1); } else { str2=str2+temp.getLabel(); t.setText(str2); } } else if(e.getActionCommand().equals("oper")) { if(str1=="") { countOper=0; first=true; } else { countOper++; if(countOper>1) { getResult(); } operator=temp.getLabel(); first=false; } } else if(e.getActionCommand().equals("清空")) { str1=""; str2=""; t.setText(""); countOper=0; first=true; error=false; } else if(e.getActionCommand().equals("=")) { if((str1=="")||(str2=="")) { countOper=0; first=true; } else { getResult(); countOper=0; } } }
public void getResult() { num1=Double.parseDouble(str1); num2=Double.parseDouble(str2); if(operator.equals("+")) { result=num1+num2; } else if(operator.equals("-")) { result=num1-num2; } else if(operator.equals("*")) { result=num1*num2; } else if(operator.equals("/")) { if(num2==0.0) { error=true; } else { result=num1/num2; } } if(error) { t.setText("error"); } else { t.setText(String.valueOf(result)); str1=String.valueOf(result); str2=""; } } public static void main(String[] args) { new Frame1(); }
}
小弟刚学JAVA 这是老师布置的一个程序题 写一个计算器的简易程序 大体我都完成了 现在我想在窗体上添加一个菜单条包括一个“ ABOURT”菜单项和“HELP”菜单项 可是老是出错 不知道能不能请大家帮忙写一个正确的 十分感谢
|