用JAVA编写计算器程序(模拟Windows计算器)
用java代码写的简易计算器(可以实现基本的加减乘除功能)

⽤java代码写的简易计算器(可以实现基本的加减乘除功能)package A;import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.MouseEvent;import java.awt.event.MouseListener;import javax.swing.*;public class Calcular3 extends JFrame implements ActionListener,MouseListener{private int m1=0,n=0;//private double m2=0;//运算的数private int flag=0;JFrame f;JPanel p1,p2,p3;JTextField t;JButton b1[]=new JButton[18];String b[]= {"1","2","3","4","5","6","7","8","9","0","清空","退格",".","=","+","-","*","/"};public Calcular3(){f=new JFrame("计算器");t=new JTextField(35);p1=new JPanel();p2=new JPanel();p3=new JPanel();f.setBounds(100, 100, 400, 200);f.add(p1,BorderLayout.NORTH);f.add(p2,BorderLayout.CENTER);f.add(p3,BorderLayout.EAST);p2.setLayout(new GridLayout(5,3));p3.setLayout(new GridLayout(4,1));p1.add(t);for(int i=0;i<14;i++) {b1[i]=new JButton(b[i]);p2.add(b1[i]);b1[i].addActionListener(this);}for(int i=14;i<18;i++) {b1[i]=new JButton(b[i]);p3.add(b1[i]);b1[i].addActionListener(this);}/*for(int i=0;i<18;i++) {b1[i].addActionListener(this);}*/f.setVisible(true);}//实现接⼝的⽅法public void mouseClicked(MouseEvent e) {}public void mousePressed(MouseEvent e) {}public void mouseReleased(MouseEvent e) {}public void mouseEntered(MouseEvent e) {}public void mouseExited(MouseEvent e) {}public void actionPerformed(ActionEvent e) {String str="";int i;for(i=0;i<=9;i++) {if(e.getSource()==b1[i]) {if(i==9) {n=n*10;}else {n=n*10+i+1;}str=String.valueOf(n);//整形n转换成字符串strt.setText(str);//显⽰到⽂本框上}}for(i=14;i<18;i++) {//+、-、*、/if(e.getSource()==b1[i]) {//匹配运算符m1=Integer.parseInt(t.getText());if(flag==15) {m2=m1+m2;}else if(flag==16) {m2=m1-m2;}else if(flag==17) {m2=m1*m2;}else if(flag==18) {m2=m1/m2;}else m2=m1;//若⽆连续的运算符运算,保存当前数据到m2 if(i==14) flag=15;else if(i==15) flag=16;else if(i==16) flag=17;else flag=18;str=String.valueOf(b[i]);t.setText(str);//显⽰到⽂本框上n=0;//还原,记录下次数据break;//找到匹配数据退出循环}}if(e.getSource()==b1[13]) {//=m1=Integer.parseInt(t.getText());if(flag==15) {m2=m2+m1;}else if(flag==16) {m2=m2-m1;}else if(flag==17) {m2=m2*m1;}else if(flag==18) {m2=m2/m1;}else m2=m1;str=String.valueOf(m2);t.setText(str);//显⽰到⽂本框上n=0;//还原,记录下次数据flag=0;//flag还原0,表明没有未处理的运算符}if(e.getSource()==b1[10]) {//各变量变为0 清空m1=0;m2=0;flag=0;n=0;t.setText("0");//显⽰到⽂本框上}if(e.getSource()==b1[11]) {//退格m1=(int)(Double.parseDouble(t.getText())/10);n=m1;str=String.valueOf(m1);t.setText(str);}if(e.getSource()==b1[12]) {//⼩数点m1=Integer.parseInt(t.getText());str=String.valueOf(m1+b[12]);t.setText(str);//显⽰到⽂本框上int j=0;for(i=0;i<=9;i++) {if(e.getSource()==b1[i]) {j++;m2=Math.pow(0.1, j)*Integer.parseInt(b[i]);str=String.valueOf(m1+m2);t.setText(str);//显⽰到⽂本框上}}}}//主函数public static void main(String[] args) {new Calcular3();}}。
【建立】java编写简单计算器

【关键字】建立今天闲着没事,用java写了一个简单计算器,能实现简单的数据计算。
语言:java开发环境:eclipse(因为是按自己的想法写的,所以有些不尽人意的地方请谅解,希望对初学java者有些许帮助,有不好理解的地方,我尽量注释,有不理解的可以在百度HI我)事先一定要安装好JDK,可以在下载,配置好环境变量,再安装好eclipse,也可以在网上下载到,具体自己去找;然后打开eclipse建立一个工程,取名随便,我这里取名Calculator;然后在建立好的工程里面新建两个包,报名也自己取,尽量易懂,容易让人理解;我这里建立了两个包,Client 和UI,等下在Client里面放的是主函数,UI里面放的是界面文件和控制器;好了下面开始写代码;一、先写界面代码:在UI包里面新建一个Class文件,取名自己想,这里我写的是CalculatorFramepackage ui;import ;import ;import ;import ;import ;import ;import ;import ;import ;import ;import ;import ;public class CalculatorFrame extends JFrame {private static final long serialVersionUID = 1L;public String opt;public String str;private JTextArea show;private ClientContext clientContext;//引用控制器东西/*因为调用了控制器里面的方法,所以要对控制器的东西进行赋值,否则运行会出现空指针异常*/public void setClientContext(ClientContext clientContext) {this.clientContext = clientContext;}public CalculatorFrame() {init();}private void init() {setTitle(" Simple Calculator");setBounds(533, 184, 300, 400);setContentPane(creatContentPane());}private JPanel creatContentPane() {JPanel p = new JPanel(new GridLayout(4, 1)); /* 在面板里面添加4个面板*/p.add(showPane());//显示屏p.add(btnPane1());//下面三个都是按钮p.add(btnPane2());p.add(btnPane3());return p;}/*实现各个面板*/private JScrollPane showPane() {JScrollPane p = new JScrollPane();p.setBorder(new TitledBorder("Display:"));show = new JTextArea();show.setFont(new Font("",Font.PLAIN,25));show.setForeground(Color.RED);show.setLineWrap(true);show.setEditable(false);p.getViewport().add(show);return p;}private JPanel btnPane1() {JPanel p = new JPanel(new GridLayout(2, 4));JButton add = new JButton("+");JButton jian = new JButton("-");JButton cheng = new JButton("*");JButton chu = new JButton("/");JButton one = new JButton("1");JButton two = new JButton("2");JButton three = new JButton("3");JButton anser = new JButton("=");p.add(add);p.add(jian);p.add(cheng);p.add(chu);p.add(one);p.add(two);p.add(three);p.add(anser);/*用内部类实现按钮监视器,后面的都是这样*/one.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent arg0) {String number = show.getText() + String.valueOf(1);//按了数字“1”按//钮后,操作显示屏,既更新一下显示屏clientContext.setNumber(number);//调用控制器里面的方法}});two.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent arg0) {String number = show.getText() + String.valueOf(2);;clientContext.setNumber(number);}});three.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubString number = show.getText() + String.valueOf(3);clientContext.setNumber(number);}});add.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent arg0) {opt = "+";clientContext.setOpt(opt);}});jian.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubopt = "-";clientContext.setOpt(opt);}});cheng.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubopt = "*";clientContext.setOpt(opt);}});chu.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubopt = "/";clientContext.setOpt(opt);}});anser.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent arg0) { str = "=";clientContext.setAnswer(str);}});return p;}private JPanel btnPane2() {JPanel p = new JPanel(new GridLayout(2, 4));JButton four = new JButton("4");JButton five = new JButton("5");JButton six = new JButton("6");JButton pi = new JButton("PI");JButton seven = new JButton("7");JButton eight = new JButton("8");JButton nine = new JButton("9");JButton com = new JButton(".");p.add(four);p.add(five);p.add(six);p.add(pi);p.add(seven);p.add(eight);p.add(nine);p.add(com);four.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubString number = show.getText() + String.valueOf(4);clientContext.setNumber(number);}});five.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubString number = show.getText() + String.valueOf(5);clientContext.setNumber(number);}});six.addActionListener(new ActionListener() {@Override// TODO Auto-generated method stubString number = show.getText() + String.valueOf(6);clientContext.setNumber(number);}});seven.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubString number = show.getText() + String.valueOf(7);clientContext.setNumber(number);}});eight.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubString number = show.getText() + String.valueOf(8);clientContext.setNumber(number);}});nine.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubString number = show.getText() + String.valueOf(9);clientContext.setNumber(number);}});com.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubsetShow(show.getText() + ".");}});pi.addActionListener(new ActionListener() {@Override// TODO Auto-generated method stubsetShow(String.valueOf(Math.PI));}});return p;}private JPanel btnPane3() {JPanel p = new JPanel(new GridLayout(2, 4));JButton zero = new JButton("0");JButton sqrt = new JButton("√");JButton guiling = new JButton("C");final JButton help = new JButton("Help");p.add(zero);p.add(sqrt);p.add(guiling);p.add(help);help.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubJOptionPane.showMessageDialog(help, "注意:假如第二运算数为空的话,这里将默认为0.0!");}});guiling.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubclientContext.setMc();}});zero.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubString number = show.getText() + String.valueOf(0);clientContext.setNumber(number);}});sqrt.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubsetShow("" + Math.sqrt(getShow()));}});return p;}/*更新计算器的显示屏*/public void setShow(String str) {show.setText(str);}/*获取当前显示屏里面的数据*/public Double getShow() {String str = show.getText();if (str.equals("")) {str = "0.0";}return Double.valueOf(str);}/*获取当前选择的运算符:比如加或减或乘或除*/public String getOpt() {return this.opt;}}二、写控制器代码在UI包建立一个Class,我取名ClientContextpackage ui;import ;import ;import ;public class ClientContext {private CalculatorFrame calculatorFrame;private Double first = 0.0;private Double next = 0.0;public void setCalculatorFrame(CalculatorFrame calculatorFrame) {this.calculatorFrame = calculatorFrame;}double sum = 0;public void setNumber(String str) {calculatorFrame.setShow(str);}public void setOpt(String opt) {first = calculatorFrame.getShow();calculatorFrame.setShow("");}public void setAnswer(String str) {//按了“=”后,对数据按运算符进行计算next = calculatorFrame.getShow();// calculatorFrame.setShow(str);// switch(str){//// }if (calculatorFrame.getOpt() == "+") {double answer = first + next;calculatorFrame.setShow(String.valueOf(answer));} else if (calculatorFrame.getOpt() == "-") {double answer = first - next;calculatorFrame.setShow(String.valueOf(answer));} else if (calculatorFrame.getOpt() == "*") {double answer = first * next;calculatorFrame.setShow(String.valueOf(answer));} else if (calculatorFrame.getOpt() == "/") {if (next == 0) {calculatorFrame.setShow("对不起,除数不能为0");} else {double answer = first / next;calculatorFrame.setShow(String.valueOf(answer));}} else {calculatorFrame.setShow(String.valueOf(calculatorFrame.getShow()));}}public void setMc() {// TODO Auto-generated method stubcalculatorFrame.setShow("");first = 0.0;next = 0.0;calculatorFrame.opt=null;}}三、写主方法在Client包里面新建Class,我取名Mainpackage client;import ;import ui.CalculatorFrame;import ui.ClientContext;public class Main {/*** @param args*/public static void main(String[] args) {// TODO Auto-generated method stubCalculatorFrame c = new CalculatorFrame();c.setVisible(true);ClientContext clientContext = new ClientContext();c.setClientContext(clientContext);clientContext.setCalculatorFrame(c);}}最后运行后如下:文档来源为:从网络收集整理.word版本可编辑.欢迎下载支持.此文档是由网络收集并进行重新排版整理.word可编辑版本!11。
java计算器程序代码

import java.awt.*;//计算器实例import java.awt.event.*;public class calculator{public static void main(String args[]){MyWindow my=new MyWindow("计算器");}}class MyWindow extends Frame implements ActionListener{ StringBuffer m=new StringBuffer();int p;TextField tex;Buttonb0,b1,b2,b3,b4,b5,b6,b7,b8,b9,jia,jian,cheng,chu,deng,dian,qingling,kaifang;MyWindow(String s){super(s);//StringBuffer s2=new StringBuffer();//String s;tex=new TextField(18);b0=new Button(" 0 ");b1=new Button(" 1 ");b2=new Button(" 2 ");b3=new Button(" 3 ");b4=new Button(" 4 ");b5=new Button(" 5 ");b6=new Button(" 6 ");b7=new Button(" 7 ");b8=new Button(" 8 ");b9=new Button(" 9 ");dian=new Button(" . ");jia=new Button(" + ");jian=new Button(" - ");cheng=new Button(" × ");chu=new Button(" / ");deng=new Button(" = ");qingling=new Button(" 清零 ");kaifang=new Button(" √ ");setLayout(new FlowLayout());add(tex);add(b0);add(b1);add(b2);add(b3);add(b4);add(b5);add(b6);add(b7);add(b8);add(b9);add(dian);add(jia);add(jian);add(cheng);add(chu);add(kaifang);add(qingling);add(deng);b0.addActionListener(this);b1.addActionListener(this);b2.addActionListener(this);b3.addActionListener(this);b4.addActionListener(this);b5.addActionListener(this);b6.addActionListener(this);b7.addActionListener(this);b8.addActionListener(this);b9.addActionListener(this);jia.addActionListener(this);jian.addActionListener(this);cheng.addActionListener(this);chu.addActionListener(this);dian.addActionListener(this);deng.addActionListener(this);qingling.addActionListener(this); kaifang.addActionListener(this);setBounds(200,200,160,280);setResizable(false);//不可改变大小setVisible(true);validate();addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent ee){ System.exit(0);}});}public void actionPerformed(ActionEvent e){if(e.getSource()==b0){m=m.append("0");tex.setText(String.valueOf(m));}if(e.getSource()==b1){m=m.append("1"); tex.setText(String.valueOf(m)); }if(e.getSource()==b2){m=m.append("2"); tex.setText(String.valueOf(m)); }if(e.getSource()==b3){m=m.append("3"); tex.setText(String.valueOf(m)); }if(e.getSource()==b4){m=m.append("4"); tex.setText(String.valueOf(m));}if(e.getSource()==b5){m=m.append("5"); tex.setText(String.valueOf(m)); }if(e.getSource()==b6){m=m.append("6"); tex.setText(String.valueOf(m)); }if(e.getSource()==b7){m=m.append("7"); tex.setText(String.valueOf(m)); }if(e.getSource()==b8){m=m.append("8"); tex.setText(String.valueOf(m)); }if(e.getSource()==b9){m=m.append("9"); tex.setText(String.valueOf(m)); }if(e.getSource()==jia){m=m.append("+"); tex.setText(String.valueOf(m)); }if(e.getSource()==jian){m=m.append("-"); tex.setText(String.valueOf(m)); }if(e.getSource()==cheng){m=m.append("*"); tex.setText(String.valueOf(m)); }if(e.getSource()==chu){m=m.append("/"); tex.setText(String.valueOf(m)); }if(e.getSource()==dian){m=m.append("."); tex.setText(String.valueOf(m)); }String mm=String.valueOf(m);int p1=mm.indexOf("+");int p2=mm.indexOf("-");int p3=mm.indexOf("*");int p4=mm.indexOf("/");if(p1!=-1){p=p1;}else if(p3!=-1){p=p3;}else if(p2!=-1){p=p2;}else if(p4!=-1){p=p4;}if(e.getSource()==deng){String m1=mm.substring(0,p);String m2=mm.substring(p+1);String ch=mm.substring(p,p+1);//System.out.println(m1);//System.out.println(m2);//System.out.println(ch);if(ch.equals("+")){float n1=Float.parseFloat(m1); float n2=Float.parseFloat(m2); float sum=n1+n2;String su=String.valueOf(sum); tex.setText(su);}if(ch.equals("-")){float n1=Float.parseFloat(m1);float n2=Float.parseFloat(m2);float sum=n1-n2;String su=String.valueOf(sum);tex.setText(su);}if(ch.equals("*")){float n1=Float.parseFloat(m1);float n2=Float.parseFloat(m2);float sum=n1*n2;String su=String.valueOf(sum);tex.setText(su);}if(ch.equals("/")){float n1=Float.parseFloat(m1);float n2=Float.parseFloat(m2);float sum=n1/n2;String su=String.valueOf(sum);tex.setText(su);}}if(e.getSource()==qingling){StringBuffer kk=new StringBuffer(); m=kk;tex.setText("0");// System.out.println(mm);}if(e.getSource()==kaifang){String t=tex.getText();float num=Float.parseFloat(t);double nub=Math.sqrt(num);tex.setText(String.valueOf(nub)); }}}。
Java实现简易计算器

Java实训作业题目:Java实现简易计算器学院:姓名:学号:班级:20 年月一、实验目的通过课程设计,主要要达到两个目的,一是检验和巩固专业知识、二是提高综合素质和能力。
此次课程设计实训主要是Java语言程序设计的实现。
通过该课程设计,可以将课堂上掌握的理论知识与处理数据的业务相结合,以检验自己掌握知识的宽度、深度及对知识的综合运用能力。
二、实验要求用Java编写一个简单的计算器,使其能够实现最基本的功能,如简单的加、减、乘、除;平方根,倒数,平方等功能。
三、详细内容1.界面设计界面设计使用GUI,其中有用到swing组件的TextField和Button,用到awt中的BorderLayout和GridLayout布局管理方式,其图形界面如图1-1所示:图1-1其中主要代码为:public mainWindow(){this.setTitle("计算器");//用户图形界面标题this.setVisible(true);//用户图形界面可缩小this.setResizable(false);//用户图形界面不可放大this.setSize(350,300);//设置用户图形界面的大小this.setLocation(400,150);//用户图形界面在屏幕中的显示位置JPanel panel1 = new JPanel();//新建一个画板JPanel panel2 = new JPanel();button1 = new JButton("1");...reset = new JButton("CE");Container container = this.getContentPane();container.add(panel2,BorderLayout.NORTH);container.add(panel1);panel1.setLayout(new GridLayout(5,4));//将画板1分为4行5列result.setEnabled(false);result.setFont(new Font("Dialog",Font.BOLD,25));//运算结果的字体大小result.setEditable(false);result.setHorizontalAlignment(SwingConstants.RIGHT);panel1.add(reciprocal);//分别将20个按钮依次添加到画板panel1中,并设置各自的大小reciprocal.setFont(new Font("Dialog",Font.PLAIN,20));...panel1.add(divide);divide.setFont(new Font("Dialog",Font.PLAIN,20));panel2.setLayout(new GridLayout());panel2.add(result);//画板panel2添加运算结果2.四则运算较为简单的实现了简单的加、减、乘、除运算,主要代码如下:ActionListener equal1 = new ActionListener(){ //实现四则运算public void actionPerformed(ActionEvent e){String str = result.getText();b = DatatypeConverter.parseDouble(str);{if(flag == "+")c = a + b;else if(flag == "-")c = a - b;else if(flag == "*")c = a * b;else if(flag == "/" || b != 0)c = a / b;}if(flag != "=")result.setText("" + c);elseresult.setText("零不能做除数!");a = 0;b = 0;c = 0;flag = "";}};3.其他功能另外添加了平方根,倒数,平方等功能,主要代码如下:平方根运算的实现:ActionListener sqrt1= new ActionListener(){public void actionPerformed(ActionEvent e){String str = result.getText();double i = DatatypeConverter.parseDouble(str);i = Math.sqrt(i);result.setText("" + i);}};倒数运算的实现:ActionListener reciprocal1 = new ActionListener(){ public void actionPerformed(ActionEvent e){String str = result.getText();double i = DatatypeConverter.parseDouble(str);i = 1/i;result.setText("" + i);}};平方运算的实现:ActionListener square1 = new ActionListener(){public void actionPerformed(ActionEvent e){String str = result.getText();double i = DatatypeConverter.parseDouble(str);i = i*i;result.setText("" + i);}};4.程序测试经测试发现本计算器基本功能均能实现,可正常运行计算,针对功能实现的代码部分过于简单,可以对其进行改善提高,方便用户使用!5.实训小结通过对计算器窗体的编写,熟悉了java图形用户界面的设计原理和程序结构,熟悉了java中awt和swing的组合。
java计算器源代码(仿win7)

java计算器源代码(仿win7)import java.awt.*;import javax.swing.*;import java.awt.event.*;class Cal extends JFrame implements ActionListener,MouseListener{JMenuBar menubar;JMenu menu_check,menu_edit,menu_help;JMenuItem menuitem_science,menuitem_check,menuitem_exit,menuitem_copy,menuitem_paste,menuitem1_copy,menuitem1_paste,menuitem_chelp,menuitem_about;JCheckBoxMenuItem menuitem_standard;JTextField ta1;int x,result2;double op1,op2,opall;private boolean end=false,flag=false,add=false,sub=false,cheng=false,chu=false,flagop2=false;JButton b_mc,b_mr,b_ms,b_mjia,b_mjian,b_tui,b_ce,b_c,b_jj,b_dui,b_7,b_8,b_9,b_chu,b_baifenhao,b_4,b_5,b_6,b_cheng,b_daoshu,b_1,b_2,b_3,b_jian,b_0,b_dian,b_jia,b_dengyu;JPanel p_all,p_button1,p_button2,p_txt,p1,p2,p3,p4,p5;private String str,resultstr;JPopupMenu popupmenu;Container con=this.getContentPane();Font font=new Font("微软雅黑",Font.PLAIN,12);Color color=new Color(120,220,120);Cal(String s){super(s);setSize(220,315);setResizable(false);setVisible(true);Dimension scr=Toolkit.getDefaultToolkit().getScreenSize();Dimension frm=this.getSize();setLocation((scr.width-frm.width)/2,(scr.height-frm.height)/2);Toolkit tk=Toolkit.getDefaultToolkit();//程序默认图标设置setIconImage(tk.createImage("D:\\sd.jpg"));setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//-----------------------------------------------------------------制作框架结构------------------------- //---------------------------------------菜单栏---------------------------menubar=new JMenuBar();menubar.setPreferredSize(new Dimension(frm.width,19));menu_check=new JMenu("查看(V)");menu_check.setFont(font);menu_check.setForeground(Color.black);menuitem_standard=new JCheckBoxMenuItem("标准型",true);menuitem_standard.setFont(font);menuitem_standard.setForeground(Color.black);menuitem_science=new JMenuItem("科学型");menuitem_science.setFont(font);menuitem_science.setForeground(Color.black);menuitem_check=new JMenuItem("查看分组");menuitem_check.setFont(font);menuitem_check.setForeground(Color.black);menuitem_exit=new JMenuItem("退出");menuitem_exit.setFont(font);menuitem_exit.setForeground(Color.black);menuitem_exit.addActionListener(this);menu_check.add(menuitem_standard);menu_check.add(menuitem_science);menu_check.addSeparator();menu_check.add(menuitem_check);menu_check.addSeparator();menu_check.add(menuitem_exit);menubar.add(menu_check);menu_edit=new JMenu("编辑(E)");menu_edit.setFont(font);menu_edit.setForeground(Color.black);menu_edit.setMnemonic(KeyEvent.VK_E);menuitem_copy=new JMenuItem("复制(C) ");menuitem_copy.setFont(font);menuitem_copy.setForeground(Color.black);menuitem_copy.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C,InputEvent.CTRL_M ASK));menuitem_copy.addActionListener(this);menuitem_paste=new JMenuItem("粘贴(P) ");menuitem_paste.setFont(font);menuitem_paste.setForeground(Color.black);menuitem_paste.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V,InputEvent.CTRL_M ASK));menuitem_paste.addActionListener(this);menu_edit.add(menuitem_copy);menu_edit.add(menuitem_paste);menubar.add(menu_edit);menu_help=new JMenu("帮助(H)");menu_help.setFont(font);menu_help.setForeground(Color.black);menuitem_chelp=new JMenuItem("查看帮助");menuitem_chelp.setFont(font);menuitem_chelp.setForeground(Color.black);menuitem_about=new JMenuItem("关于计算器");menuitem_about.setFont(font);menuitem_about.setForeground(Color.black);menuitem_about.addActionListener(this);menu_help.add(menuitem_chelp);menu_help.addSeparator();menu_help.add(menuitem_about);menubar.add(menu_help);setJMenuBar(menubar);//--------------------------------------文本框----------------------------------ta1=new JTextField("0");ta1.setFont(new Font("微软雅黑",Font.PLAIN,13));ta1.setEditable(false);//ta1.setOpaque(false);ta1.setHorizontalAlignment(JTextField.RIGHT);ta1.setPreferredSize(new Dimension((frm.width-26),45));ta1.addMouseListener(this);p_all=new JPanel();p_all.setPreferredSize(new Dimension((frm.width-6),250));//p_all.setBackground(color);p_all.setLayout(new FlowLayout(FlowLayout.CENTER,0,3));p_txt=new JPanel();p_txt.setPreferredSize(new Dimension((frm.width-6),53));p_txt.setLayout(new FlowLayout(FlowLayout.CENTER,0,7));p_txt.add(ta1);p_all.add(p_txt);con.add(p_all,BorderLayout.CENTER);//-------------------------------------按钮区----------------------------------p_button1=new JPanel();p_button1.setPreferredSize(new Dimension((frm.width-25),131)); p_button1.setLayout(new FlowLayout(FlowLayout.LEFT,0,3));p_all.add(p_button1);p1=new JPanel();p1.setPreferredSize(new Dimension((frm.width-25),127));p1.setLayout(new GridLayout(4,5,5,6));b_mc=new JButton("MC");b_mc.setFont(new Font("微软雅黑",Font.PLAIN,11));b_mc.setMargin(new Insets(0,0,0,0));b_mc.setForeground(Color.blue);b_mc.addActionListener(this);b_mr=new JButton("MR");b_mr.setFont(new Font("微软雅黑",Font.PLAIN,11));b_mr.setMargin(new Insets(0,0,0,0));b_mr.setForeground(Color.blue);b_mr.addActionListener(this);b_ms=new JButton("MS");b_ms.setFont(new Font("微软雅黑",Font.PLAIN,11));b_ms.setMargin(new Insets(0,0,0,0));b_ms.setForeground(Color.blue);b_ms.addActionListener(this);b_mjia=new JButton("M+");b_mjia.setFont(new Font("微软雅黑",Font.PLAIN,11));b_mjia.setMargin(new Insets(0,0,0,0));b_mjia.setForeground(Color.blue);b_mjia.addActionListener(this);b_mjian=new JButton("M-");b_mjian.setFont(new Font("微软雅黑",Font.PLAIN,11)); b_mjian.setMargin(new Insets(0,0,0,0));b_mjian.setForeground(Color.blue);b_mjian.addActionListener(this);b_tui=new JButton("←");b_tui.setFont(new Font("微软雅黑",Font.BOLD,14));b_tui.setMargin(new Insets(0,0,0,0));b_tui.addActionListener(this);b_tui.setForeground(Color.red);b_ce=new JButton("CE");b_ce.setFont(new Font("微软雅黑",Font.PLAIN,11));b_ce.setMargin(new Insets(0,0,0,0));b_ce.setForeground(Color.red);b_ce.addActionListener(this);b_c=new JButton("C");b_c.setFont(new Font("微软雅黑",Font.PLAIN,11));b_c.setMargin(new Insets(0,0,0,0));b_c.setForeground(Color.red);b_c.addActionListener(this);b_jj=new JButton("±");b_jj.setFont(new Font("微软雅黑",Font.PLAIN,14));b_jj.setMargin(new Insets(0,0,0,0));b_jj.setForeground(Color.red);b_jj.addActionListener(this);b_dui=new JButton("√");b_dui.setFont(new Font("微软雅黑",Font.PLAIN,11)); b_dui.setMargin(new Insets(0,0,0,0));b_dui.setForeground(Color.red);b_dui.addActionListener(this);b_7=new JButton("7");b_7.setFont(new Font("微软雅黑",Font.PLAIN,14));b_7.setMargin(new Insets(0,0,0,0));b_7.setForeground(Color.blue);b_7.setMnemonic(KeyEvent.VK_7);b_7.addActionListener(this);b_8=new JButton("8");b_8.setFont(new Font("微软雅黑",Font.PLAIN,14));b_8.setMargin(new Insets(0,0,0,0));b_8.setForeground(Color.blue);b_8.setMnemonic(KeyEvent.VK_8);b_8.addActionListener(this);b_9=new JButton("9");b_9.setMargin(new Insets(0,0,0,0));b_9.setForeground(Color.blue);b_9.setMnemonic(KeyEvent.VK_9);b_9.addActionListener(this);b_chu=new JButton("/");b_chu.setFont(new Font("微软雅黑",Font.PLAIN,14));b_chu.setMargin(new Insets(0,0,0,0));b_chu.setForeground(Color.red);b_chu.addActionListener(this);b_baifenhao=new JButton("%");b_baifenhao.setFont(new Font("微软雅黑",Font.PLAIN,11)); b_baifenhao.setMargin(new Insets(0,0,0,0));b_baifenhao.setForeground(Color.blue);b_baifenhao.addActionListener(this);b_4=new JButton("4");b_4.setFont(new Font("微软雅黑",Font.PLAIN,14));b_4.setMargin(new Insets(0,0,0,0));b_4.setForeground(Color.blue);b_4.setMnemonic(KeyEvent.VK_4);b_4.addActionListener(this);b_5=new JButton("5");b_5.setFont(new Font("微软雅黑",Font.PLAIN,14));b_5.setMargin(new Insets(0,0,0,0));b_5.setForeground(Color.blue);b_5.setMnemonic(KeyEvent.VK_5);b_5.addActionListener(this);b_6=new JButton("6");b_6.setFont(new Font("微软雅黑",Font.PLAIN,14));b_6.setMargin(new Insets(0,0,0,0));b_6.setForeground(Color.blue);b_6.setMnemonic(KeyEvent.VK_6);b_6.addActionListener(this);b_cheng=new JButton("*");b_cheng.setFont(new Font("微软雅黑",Font.PLAIN,14));b_cheng.setMargin(new Insets(0,0,0,0));b_cheng.setForeground(Color.red);b_cheng.addActionListener(this);b_daoshu=new JButton("1/x");b_daoshu.setFont(new Font("微软雅黑",Font.PLAIN,11)); b_daoshu.setMargin(new Insets(0,0,0,0));b_daoshu.setForeground(Color.blue);b_daoshu.addActionListener(this);b_1=new JButton("1");b_1.setMargin(new Insets(0,0,0,0));b_1.setForeground(Color.blue);b_1.setMnemonic(KeyEvent.VK_1);b_1.addActionListener(this);b_2=new JButton("2");b_2.setFont(new Font("微软雅黑",Font.PLAIN,14)); b_2.setMargin(new Insets(0,0,0,0));b_2.setForeground(Color.blue);b_2.setMnemonic(KeyEvent.VK_2);b_2.addActionListener(this);b_3=new JButton("3");b_3.setFont(new Font("微软雅黑",Font.PLAIN,14)); b_3.setMargin(new Insets(0,0,0,0));b_3.setForeground(Color.blue);b_3.setMnemonic(KeyEvent.VK_3);b_3.addActionListener(this);b_jian=new JButton("-");b_jian.setFont(new Font("微软雅黑",Font.PLAIN,14)); b_jian.setMargin(new Insets(0,0,0,0));b_jian.setForeground(Color.red);b_jian.addActionListener(this);b_0=new JButton("0");b_0.setFont(new Font("微软雅黑",Font.PLAIN,14)); b_0.setMargin(new Insets(0,0,0,0));b_0.setPreferredSize(new Dimension(75,27));b_0.setForeground(Color.blue);b_0.setMnemonic(KeyEvent.VK_0);b_0.addActionListener(this);JLabel L1=new JLabel();L1.setPreferredSize(new Dimension(5,3));b_dian=new JButton(".");b_dian.setFont(new Font("微软雅黑",Font.BOLD,14)); b_dian.setMargin(new Insets(0,0,0,0));b_dian.setPreferredSize(new Dimension(35,27));b_dian.setForeground(Color.blue);b_dian.addActionListener(this);JLabel L2=new JLabel();L2.setPreferredSize(new Dimension(5,3));b_jia=new JButton("+");b_jia.setFont(new Font("微软雅黑",Font.BOLD,14)); b_jia.setMargin(new Insets(0,0,0,0));b_jia.setPreferredSize(new Dimension(35,27));b_jia.setForeground(Color.red);b_jia.addActionListener(this);b_dengyu=new JButton("=");b_dengyu.setFont(new Font("微软雅黑",Font.BOLD,22));b_dengyu.setMargin(new Insets(0,0,0,0));b_dengyu.setPreferredSize(new Dimension(35,60));b_dengyu.setForeground(Color.blue);b_dengyu.addActionListener(this);p1.add(b_mc);p1.add(b_mr);p1.add(b_ms);p1.add(b_mjia);p1.add(b_mjian);p1.add(b_tui);p1.add(b_ce);p1.add(b_c);p1.add(b_jj);p1.add(b_dui);p1.add(b_7);p1.add(b_8);p1.add(b_9);p1.add(b_chu);p1.add(b_baifenhao);p1.add(b_4);p1.add(b_5);p1.add(b_6);p1.add(b_cheng);p1.add(b_daoshu);p_button1.add(p1);p_button2=new JPanel();p_button2.setPreferredSize(new Dimension((frm.width-24),65)); p_button2.setLayout(new FlowLayout(FlowLayout.LEFT,0,0));p_all.add(p_button2);p2=new JPanel();p2.setPreferredSize(new Dimension(156,65));p2.setLayout(new FlowLayout(FlowLayout.LEFT,0,1));p3=new JPanel();p3.setPreferredSize(new Dimension(39,62));p3.setLayout(new FlowLayout(FlowLayout.LEFT,4,0));p_button2.add(p2);p_button2.add(p3);p4=new JPanel();p4.setPreferredSize(new Dimension(156,27));p4.setLayout(new GridLayout(1,4,5,5));p5=new JPanel();p5.setPreferredSize(new Dimension(156,39));p5.setLayout(new FlowLayout(FlowLayout.LEFT,0,5));p2.add(p4);p2.add(p5);p4.add(b_1);p4.add(b_2);p4.add(b_3);p4.add(b_jian);p5.add(b_0);p5.add(L1);p5.add(b_dian);p5.add(L2);p5.add(b_jia);p3.add(b_dengyu);//---------------------------------------快捷菜单对象-------------------------popupmenu=new JPopupMenu(); //快捷菜单对象menuitem1_copy=new JMenuItem("复制");menuitem1_copy.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C,InputEvent.CTRL_ MASK));menuitem1_copy.addActionListener(this); //监视鼠标右击菜单”复制“popupmenu.add(menuitem1_copy);menuitem1_paste=new JMenuItem("粘贴");menuitem1_paste.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V,InputEvent.CTRL_MASK));menuitem1_paste.addActionListener(this); //监视鼠标右击菜单”粘贴“popupmenu.add(menuitem1_paste);ta1.add(popupmenu);con.validate();validate();}//---------------------------------------功能区------------------------------------public void actionPerformed(ActionEvent e){if(e.getSource()==menuitem_about){JOptionPane.showMessageDialog(null,"这是一个模仿win7的计算器!欢迎改进,\n创作者:钟作明","仿win7计算器",RMATION_MESSAGE);}if(e.getSource()==menuitem1_copy){ta1.selectAll();ta1.copy();}else if(e.getSource()==menuitem1_paste){ta1.setEditable(true);ta1.setText("");ta1.paste();ta1.setEditable(false);}else if(e.getSource()==menuitem_copy){ta1.selectAll();ta1.copy();}else if(e.getSource()==menuitem_paste){ta1.setEditable(true);ta1.setText("");ta1.paste();ta1.setEditable(false);}else if(e.getSource()==menuitem_exit){System.exit(0);}else if(e.getSource()==b_ce){ta1.setEditable(true);ta1.setText("0");ta1.setEditable(false);}else if(e.getSource()==b_c){ta1.setEditable(true);ta1.setText("0");ta1.setEditable(false);}else if(e.getSource()==b_tui){String str=ta1.getText();StringBuffer s=new StringBuffer(str);int L=s.length();try{if(L!=1){s=s.deleteCharAt(L-1);}else{s=new StringBuffer("0");}}catch(Exception e1){}ta1.setText(String.valueOf(s));}//---------------------------------------------数字键----------------------------- if(e.getSource()==b_1){addString(1);}else if(e.getSource()==b_2){addString(2);}else if(e.getSource()==b_3){addString(3);}else if(e.getSource()==b_4){addString(4);}else if(e.getSource()==b_5){addString(5);}else if(e.getSource()==b_6){addString(6);}else if(e.getSource()==b_7){addString(7);}else if(e.getSource()==b_8){addString(8);}else if(e.getSource()==b_9){addString(9);}else if(e.getSource()==b_0){addString(0);}else if(e.getSource()==b_dian){StringBuffer s1=new StringBuffer(ta1.getText());StringBuffer dian=new StringBuffer(".");if(String.valueOf(s1).indexOf(".")==-1){s1.append(dian);}ta1.setText(String.valueOf(s1));}else if(e.getSource()==b_jj){String txt=ta1.getText();int result=Integer.parseInt(txt);if(txt.indexOf("-")==-1&&txt.length()>0){if(result!=0){txt="-"+txt;}}else{StringBuffer txt1=new StringBuffer(txt);txt1=txt1.deleteCharAt(0);txt=String.valueOf(txt1);}ta1.setText(txt);}else if(e.getSource()==b_dui){str=ta1.getText();Double d=Double.parseDouble(str);if(d>=0){double d1=Math.sqrt(d);String s = String.valueOf(d1);if(s.endsWith(".0")==true){int z=(int)d1;str=String.valueOf(z);}else{str=String.valueOf(d1);}ta1.setText(str);}else{JOptionPane.showMessageDialog(null,"根号底数不能为负数","提醒", RMATION_MESSAGE);}end=true;}else if(e.getSource()==b_baifenhao){str=ta1.getText();Double d=Double.parseDouble(str);ta1.setText(""+d/100);end=true;}else if(e.getSource()==b_daoshu){str=ta1.getText();Double d=Double.parseDouble(str);if(d!=0){ta1.setText(""+1/d);}else{JOptionPane.showMessageDialog(null,"除数不能为零","提醒", RMATION_MESSAGE);}end=true;}else if(e.getSource()==b_jia){str = ta1.getText();op1 = Double.parseDouble(str);end=true;x=0;opall=op1;flagop2=false;}else if(e.getSource()==b_jian){str = ta1.getText();op1 = Double.parseDouble(str);end=true;x=1;opall=op1;flagop2=false;}else if(e.getSource()==b_cheng){str = ta1.getText();op1 = Double.parseDouble(str);end=true;x=2;opall=op1;flagop2=false;}else if(e.getSource()==b_chu){str = ta1.getText();op1 = Double.parseDouble(str);end=true;x=3;opall=op1;flagop2=false;}else if(e.getSource()==b_dengyu){str = ta1.getText();if(flagop2==false){op2 = Double.parseDouble(str);flagop2=true;}switch(x){case 0 :opall=opall+op2;String s=String.valueOf(opall);if(s.endsWith(".0")==true){result2=(int)opall;resultstr=String.valueOf(result2);}else{resultstr=String.valueOf(opall);}ta1.setText(resultstr);break;case 1 :opall=opall-op2;s=String.valueOf(opall);if(s.endsWith(".0")==true){result2=(int)opall;resultstr=String.valueOf(result2);}else{resultstr=String.valueOf(opall);}ta1.setText(resultstr);break;case 2 :opall=opall*op2;s=String.valueOf(opall);if(s.endsWith(".0")==true){result2=(int)opall;resultstr=String.valueOf(result2);}else{resultstr=String.valueOf(opall);}ta1.setText(resultstr);break;case 3 :opall=opall/op2;s=String.valueOf(opall);if(s.endsWith(".0")==true){result2=(int)opall;resultstr=String.valueOf(result2);}else{resultstr=String.valueOf(opall);}ta1.setText(resultstr);break;}end=true;}}public void addString(int num){String s=null;s=String.valueOf(num);//如果end==true;,那么屏幕清空if(end==true){ta1.setText("0");end=false;}if((ta1.getText()).equals("0")){ta1.setText(s);}else{if(ta1.getText().length()<21){str=ta1.getText()+s;ta1.setText(str);}}}public void mouseClicked(MouseEvent mec){if(mec.getModifiers()==mec.BUTTON3_MASK){popupmenu.show(ta1,mec.getX(),mec.getY());}}public void mousePressed(MouseEvent ms){}public void mouseReleased(MouseEvent md){}public void mouseEntered(MouseEvent ms){}public void mouseExited(MouseEvent mex){}public void mouseDragged(MouseEvent med){}}public class Calculator {public static void main(String[] args) {// TODO Auto-generated method stubCal jishuanji=new Cal("计算器");}}。
JavaSwing实现仿win7计算器

JavaSwing实现仿win7计算器⾸先说明此代码的界⾯布局基本上参考了:由于后⾯的运算符处理操作实在难以理解。
所以后⾯事件的处理是⾃⼰改写的,我觉得这样⽐较好理解。
/****/package myJavaSwing;import javax.swing.JFrame;import java.awt.event.ActionListener;import java.awt.event.ActionEvent;import javax.swing.JButton;import javax.swing.JTextField;import javax.swing.JPanel;import java.awt.GridLayout;import java.awt.Color;import java.awt.BorderLayout;import java.awt.Container;/*** @author 花花*简介:仿windows7计算器*由于M键设计到存储器暂不⽀持M键的功能**/public class Calculator extends JFrame implements ActionListener {//计算器的三个功能键名字private final String COMMAND[]= {"Backspace","CE","C"};//计算计算⾯板上的键名private final String CALCULATE[]= {"7","8","9","/","sqrt","4","5","6","*","%","1","2","3","-","1/x","0","+/-",".","+","="};//计算器上的M键名private final String M[]= {" ","MC","MR","MS","M+"};//定义三个功能按钮JButton commands[]=new JButton[COMMAND.length];//定义计算⾯板班的按钮JButton calculate[]=new JButton[CALCULATE.length];//定义M按钮JButton m[]=new JButton[M.length];//结果⽂本框JTextField resultText=new JTextField();//计算结果private double result=0;//⽂本框中之前是否有输⼊private Boolean preferExist=false;//操作符private String op="=";//是否按了操作符private Boolean operate=false;//中间值。
java实验报告——简单计算器的编写五篇范文

java实验报告——简单计算器的编写五篇范文第一篇:java实验报告——简单计算器的编写JAVA实验报告——简单计算器的编写班级:学号:姓名:一、实验目的1.掌握java图形用户界面(GUI)的设计原理和程序结构2.能设计复核问题要求的图形用户界面程序3.掌握常用组件的事件接口4.应用awt和swing组件进行应用程序设计二、实验条件1.计算机一台2.java软件开发环境三、实验步骤1、编写代码:mport java.awt.*;import java.awt.event.*;import javax.swing.*;public class JCalculator extends JFrame implements ActionListener {private static final long serialVersionUID =-***457Lprivate class WindowCloser extends WindowAdapter {public void windowClosing(WindowEvent we){System.exit(0);}}int i;private final String[] str = { “7”, “8”, “9”, “/”, “4”, “5”, “6”, “*”, “1”,“2”, “3”, “-”, “.”, “0”, “=”, “+” };JButton[] buttons = new JButton[str.length]; JButton reset = new JButton(“CE”); JTextField display = new JTextField(“0”);public JCalculator(){super(“Calculator”);JPanel panel1 = new JPanel(new GridLayout(4, 4)); for(i = 0;i < str.length;i++){buttons[i] = new JButton(str[i]);panel1.add(buttons[i]);}JPanel panel2 = new JPanel(new BorderLayout()); panel2.add(“Center”, display);panel2.add(“East”, reset);getContentPane().setLayout(new BorderLayout()); getContentPane().add(“North”, panel2); getContentPane().add(“Center”, panel1);for(i = 0;i < str.length;i++)buttons[i].addActionListener(this);reset.addActionListener(this);display.addActionListener(this); addWindowListener(new WindowCloser()); setSize(800, 800);setVisible(true);pack();}public void actionPerformed(ActionEvent e){ Object target = e.getSource();String label = e.getActionCommand();if(target == reset)handleReset();else if(“0123456789.”.indexOf(label)> 0)handleNumber(label);elsehandleOperator(label);}boolean isFirstDigit = true;public void handleNumber(String key){if(isFirstDigit)display.setText(key);else if((key.equals(“.”))&&(display.getText().indexOf(“.”)< 0))display.setText(display.getText()+ “.”);else if(!key.equals(“.”))display.setText(display.getText()+ key);isFirstDigit = false;}public void handleReset(){display.setText(“0”);isFirstDigit = true;operator = “=”;}double number = 0.0;String operator = “=”;public void handleOperator(String key){if(operator.equals(“+”))number += Double.valueOf(display.getText());else if(operator.equals(“-”))number-= Double.valueOf(display.getText());else if(operator.equals(“*”))number *= Double.valueOf(display.getText());else if(operator.equals(“/”))number /= Double.valueOf(display.getText());else if(operator.equals(“=”))number = Double.valueOf(display.getText());display.setText(String.valueOf(number));operator = key;isFirstDigit = true;}public static void main(String[] args){new JCalculator();} }2、运行结果,见截图计算测试:123+456=579结果正确,程序无误。
java计算器代码及实验报告

一、实验内容题目:1、设计一个计算器要求:1、使用layout进行布局,使界面更加友好2、实现整数的加减乘除运算(不考虑优先级)二、实验过程(这是实验报告极其重要的内容。
要抓住重点,可以从理论和实践两个方面考虑。
这部分要写明依据什么知识点以及使用方法进行实验以及实验步骤。
不要简单照抄实习指导,更不可写一大堆源代码)二、实验过程1、进行计算器界面的布局:a 、Panel的嵌套布局:主要设置了七个Panel来将界面分成几个部分。
且Panel都是用borderLayout来进行的布局。
如图所示,其中4、5、6、7分别表示Panel4、Panel5、Panel6、Panel7Panel2由Panel4、Panel5组成;Panel3由Panel6、Panel7组成;Panel1由Panel2、Panel3组成;b、(1)、在Panel6添加一个按钮并将border设置成LoweredBevel,设置按钮大小,并给按钮命名(2)、将Panel7的layout 设置成FlowLayout,并添加三个按钮,设置按钮大小,并给按钮命名(3)、将Panel5的layout 设置成gridLayout,并添加四个按钮,设置按钮大小,并给按钮命名(4)、将Panel4的layout 设置成gridLayout,并添加二十个按钮,设置按钮大小,并给按钮命名2、给对应按钮添加方法,实现起相应的功能三、实验结果1、计算器界面2、实现功能能进行整数基本的加减乘除运算、及其连续运算、清零。
四、讨论与分析1、此实验主要是进行计算器界面的布局,根据电脑上的计算器设计布局主要设置了七个Panel来将界面分成几个部分。
且Panel都是用borderLayout来进行的布局。
2、刚刚开始不能实现连续运算,本程序的设计思路是,读取两次文本框的内容赋值给a,b。
后来在原来的基础上增加了一个标志位,判断符号是不是第一次输入,如果不是则调用等于按钮功能,实现与等于相同的功能。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
用JAVA编写计算器程序(模拟Windows计算器)import java.awt.*;import java.awt.event.*;public class Calculation extends WindowAdapter implements ActionListener{double dResult=0;double dNowInput=0;double dMemory;int n=0; //记载小数位数int nOperation=1; // 记录运算符类型int nBitsNum=0; //记录总共输入的位数boolean alreadyHaveDot=false; //已经有小数点?boolean keyAvailable=true;boolean alreadyClickedEqueal=false; //是否按下过"="?boolean isTempNowInput=false; //是否在计算出结果后直接按运算符将结果赋给了当前输入值?Frame f;Panel p1,p2,p3,p4,p5,p6;TextField tf1,tf2;Button b1,b2,b3,b4,b5,b6,b7,b8,b9,b0;Button bDiv,bSqrt,bMulti,bMinus,bPercent,bPlus,bReciprocal,bEqual,bDot,bNegative; Button bBackspace,bCE,bC,bMR,bMS,bMC,bM;public void display(){f=new Frame("计算器");f.setSize(280,213);f.setLocation(200,200);f.setBackground(Color.LIGHT_GRAY);f.setResizable(false);f.setLayout(new BorderLayout(3,3));p1=new Panel(new GridLayout(1,3,5,5)); //用于存放backspace,ce,c三键p2=new Panel(new GridLayout(4,5,5,5)); //用于存放数字区及附近共20键, 此处间隙设置可能不合理,以后调整p3=new Panel(new GridLayout(5,1,5,5)); //用于存放MC,MR,MS,M+键及显示M状态文本框,此处间隙设置可能不合理,以后调整p4=new Panel(new FlowLayout()); //用于存放p1,p2p5=new Panel(new FlowLayout());p6=new Panel(new FlowLayout());p4.add(p1);p4.add(p2);tf1=new TextField(35); //存放显示区tf1.setText("0.");tf1.setEditable(false);p5.add(tf1);f.add(p5,BorderLayout.NORTH);f.add(p4,BorderLayout.CENTER);f.add(p3,BorderLayout.WEST);b1=new Button("1");b2=new Button("2");b3=new Button("3");b4=new Button("4");b5=new Button("5");b6=new Button("6");b7=new Button("7");b8=new Button("8");b9=new Button("9");b0=new Button("0");b1.addActionListener(this);b2.addActionListener(this);b3.addActionListener(this);b4.addActionListener(this);b5.addActionListener(this);b6.addActionListener(this);b7.addActionListener(this);b8.addActionListener(this);b9.addActionListener(this);b0.addActionListener(this);bDiv=new Button("/");bSqrt=new Button("sqrt"); bMulti=new Button("*"); bMinus=new Button("-"); bPercent=new Button("%"); bPlus=new Button("+"); bReciprocal=new Button("1/x"); bEqual=new Button("=");bDot=new Button("."); bNegative=new Button("+/-");bDiv.addActionListener(this); bSqrt.addActionListener(this);bMulti.addActionListener(this); bMinus.addActionListener(this); bPercent.addActionListener(this); bPlus.addActionListener(this); bReciprocal.addActionListener(this); bEqual.addActionListener(this); bDot.addActionListener(this); bNegative.addActionListener(this);p2.add(b7);p2.add(b8);p2.add(b9);p2.add(bDiv);p2.add(bSqrt);p2.add(b4);p2.add(b5);p2.add(b6);p2.add(bMulti);p2.add(bPercent);p2.add(b1);p2.add(b2);p2.add(b3);p2.add(bMinus);p2.add(bReciprocal);p2.add(b0);p2.add(bNegative);p2.add(bDot);p2.add(bPlus);p2.add(bEqual);bBackspace=new Button("Backspace"); bCE=new Button("CE");bC=new Button("C");bBackspace.addActionListener(this); bCE.addActionListener(this);bC.addActionListener(this);p1.add(bBackspace);p1.add(bCE);p1.add(bC);tf2=new TextField(2);tf2.setEnabled(false);tf2.setBackground(Color.LIGHT_GRAY); bMC=new Button("MC");bMR=new Button("MR");bMS=new Button("MS");bM=new Button("M+");bMC.addActionListener(this);bMR.addActionListener(this);bMS.addActionListener(this);bM.addActionListener(this);p6.add(tf2);p3.add(p6);p3.add(bMC);p3.add(bMR);p3.add(bMS);p3.add(bM);f.setVisible(true);f.addWindowListener(this);}public void actionPerformed(ActionEvent e){//key 0 to 9if(this.keyAvailable && e.getActionCommand().length()==1 && e.getActionComman d().compareTo("0")>=0 && e.getActionCommand().compareTo("9")<=0){if(this.isTempNowInput){this.dNowInput=0;this.isTempNowInput=false;}this.nBitsNum++;if(this.alreadyHaveDot==false)this.dNowInput=this.dNowInput*10+Double.parseDouble(e.getActionCommand()); else{double temp=Double.parseDouble(e.getActionCommand());for(int i=this.n;i<0;i++){temp*=0.1;}this.dNowInput+=temp;this.n--;}this.tf1.setText(Double.toString(this.dNowInput));}// key dotif(this.keyAvailable && e.getActionCommand()=="."){if(this.alreadyHaveDot==false){this.nBitsNum++;this.alreadyHaveDot=true;this.n=-1;}}//key "+","-","*","/"if(this.keyAvailable && e.getActionCommand()=="+" || e.getActionCommand()=="-" || e.getActionCommand()=="*" || e.getActionCommand()=="/"){if(this.alreadyClickedEqueal){this.dNowInput=this.dResult;this.isTempNowInput=true;}else{switch(this.nOperation){case 1: this.dResult+=this.dNowInput; break;case 2: this.dResult-=this.dNowInput; break;case 3: this.dResult*=this.dNowInput; break;case 4:{if(this.dNowInput==0){tf1.setText("除数不能为零");this.keyAvailable=false;}else this.dResult=this.dResult/this.dNowInput;}}if(this.keyAvailable)tf1.setText(Double.toString(this.dResult)); this.dNowInput=0;}if(e.getActionCommand()=="+"){this.nOperation=1;}if(e.getActionCommand()=="-"){this.nOperation=2;}if(e.getActionCommand()=="*"){this.nOperation=3;}if(e.getActionCommand()=="/"){this.nOperation=4;}this.nBitsNum=0;this.alreadyClickedEqueal=false;}// key "+/-"if(this.keyAvailable && e.getActionCommand()=="+/-") {this.dNowInput=0-this.dNowInput;tf1.setText(Double.toString(this.dNowInput));}// key "C"if(e.getActionCommand()=="C"){this.nBitsNum=0;this.dResult=0;this.dNowInput=0;this.alreadyHaveDot=false;this.n=0;this.nOperation=1;this.keyAvailable=true;this.alreadyClickedEqueal=false;tf1.setText("0.");}// key "CE"if(e.getActionCommand()=="CE"){this.nBitsNum=0;this.dNowInput=0;this.alreadyHaveDot=false;this.n=0;this.nOperation=1;this.keyAvailable=true;tf1.setText("0.");}// key "sqrt"if(this.keyAvailable && e.getActionCommand()=="sqrt") {if(this.alreadyClickedEqueal){if(this.dResult>=0){this.dResult=Math.sqrt(this.dResult);tf1.setText(Double.toString(this.dResult));}else{tf1.setText("函数输入无效");this.keyAvailable=false;}}else{if(this.dNowInput>=0){this.dNowInput=Math.sqrt(this.dNowInput);tf1.setText(Double.toString(this.dNowInput));}else{tf1.setText("函数输入无效");this.keyAvailable=false;}}// key "1/x"if(this.keyAvailable && e.getActionCommand()=="1/x") {if(this.dNowInput==0){tf1.setText("除数不能为零");this.keyAvailable=false;}else{this.dNowInput=1/this.dNowInput;tf1.setText(Double.toString(this.dNowInput));}}// key "="if(this.keyAvailable && e.getActionCommand()=="=") {this.alreadyClickedEqueal=true;switch(this.nOperation){case 1: this.dResult+=this.dNowInput; break;case 2: this.dResult-=this.dNowInput; break;case 3: this.dResult*=this.dNowInput; break;case 4:{if(this.dNowInput==0){tf1.setText("除数不能为零");this.keyAvailable=false;else this.dResult=this.dResult/this.dNowInput;}}if(this.keyAvailable)tf1.setText(Double.toString(this.dResult)); }// key "MS"if(this.keyAvailable && e.getActionCommand()=="MS"){this.dMemory=this.dNowInput;if(this.dMemory!=0)tf2.setText("M");}// key "MC"if(this.keyAvailable && e.getActionCommand()=="MC"){this.dMemory=0;tf2.setText("");}// key "MR"if(this.keyAvailable && e.getActionCommand()=="MR"){this.dNowInput=this.dMemory;tf1.setText(Double.toString(this.dNowInput));}// key "M+"if(this.keyAvailable && e.getActionCommand()=="M+"){this.dMemory+=this.dNowInput;if(this.dMemory!=0)tf2.setText("M");else tf2.setText("");}// key "%"if(this.keyAvailable && e.getActionCommand()=="%"){this.dNowInput=(this.dResult*this.dNowInput)/100;tf1.setText(Double.toString(this.dNowInput));}// key "Backspace"if(this.keyAvailable && e.getActionCommand()=="Backspace") {if(!this.alreadyClickedEqueal){if(this.dNowInput!=0){if(this.alreadyHaveDot){if(this.n==-1){this.alreadyHaveDot=false;this.n=0;}else{String str,str1;str=tf1.getText();str1=str.substring(0,this.nBitsNum-1);this.nBitsNum--;this.n++;this.dNowInput=Double.parseDouble(str1);tf1.setText(Double.toString(this.dNowInput));}}else{int temp;temp=(int)(this.dNowInput/10);this.dNowInput=(double)temp;tf1.setText(Double.toString(this.dNowInput));}}}}}public static void main(String args[]){Calculation cal=new Calculation();cal.display();}public void windowClosing(WindowEvent e){System.exit(0);}}。