基于Java的计算器算法(源代码).(精选)
用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简易计算器程序源代码package myText;import java.awt.*;import javax.swing.*;import java.awt.event.*;import javax.swing.border.*;public class Calculator extends JFrame implements ActionListener{ private JPanel Panel1=new JPanel();private JPanel Panel2=new JPanel();private JTextField tfResult=new JTextField(25);private JLabel label=new JLabel("计算结果:");private String recentOperation=null;private String recentNum=null;private boolean isNew=true;public void addButton(Container c,String s){JButton b=new JButton(s);b.setFont(new java.awt.Font("SansSerif",0,12));b.setForeground(Color.red);b.setBorder(BorderFactory.createRaisedBevelBorder());c.add(b);b.addActionListener(this);}//end public void addButton(Container c,String s)public void actionPerformed(ActionEvent e){String s=e.getActionCommand();if(s.charAt(0)>='0'&&s.charAt(0)<='9'){if(!isNew){tfResult.setText(tfResult.getText()+s);}//end if(!isNew)else{tfResult.setText(s);}//end elseisNew=false;}//end if(s.charAt(0)>='0'&&s.charAt(0)<='9') else if(s.equals(".")){if(tfResult.getText().indexOf(".")!=-1)return;if(!isNew&&tfResult.getText()!=""){tfResult.setText(tfResult.getText()+".");}//end ifelse{tfResult.setText("0.");}//end elseisNew=false;}//end if(s.equals("."))else if(s.equals("=")){equalaction(e);}//end if(s.equals("="))else{if((tfResult.getText()).equals("")){return;}//endif((tfResult.getText()).equals(""))if(recentOperation!=null){equalaction(e);}//end if(recentOperation!=null) recentOperation=s;recentNum=tfResult.getText();isNew=true;}//end else}//end public void actionPerformed(ActionEvent e) void equalaction(ActionEvent e){if(recentOperation==null||recentNum==null||tfResult.getTex t().equals("")){ return;}//end if()double last=0,now=0;try{last=Double.parseDouble(recentNum);now=Double.parseDouble(tfResult.getText());}//end trycatch(NumberFormatException ne){recentOperation=null;recentNum=null;tfResult.setText("数据输入不合法");System.out.println("数据输入不合法");isNew=true;return;}//end catch(NumberFormatException ne)if(recentOperation.equals("+")){last+=now;}//end if(recentOperation.equals("+"))if(recentOperation.equals("-")){last-=now;}//endif(recentOperation.equals("-"))if(recentOperation.equals("*")){last*=now;}//endif(recentOperation.equals("*"))if(recentOperation.equals("/")){last/=now;}//endif(recentOperation.equals("/"))tfResult.setText(""+last);recentNum=tfResult.getText();recentOperation=null;isNew=true;}//end void equalaction(ActionEvent e)public Calculator(){tfResult.setBorder(BorderFactory.createLoweredBevelBorder ());tfResult.setEditable(false);tfResult.setText("0");tfResult.setHorizontalAlignment(SwingConstants.RIGHT);////本java源代码由839682048整理修改//////Panel1.add(label,FlowLayout.LEFT);Panel1.add(tfResult);////本java源代码由839682048整理修改///Panel2.setLayout(new GridLayout(4,4,2,2));String buttons="789/456*123-0.=+";for(int i=0;i<buttons.length();i++){< p="">addButton(Panel2,buttons.substring(i,i+1));}//end for()//本java源代码由839682048整理修改///this.getContentPane().add(Panel1,"North");this.getContentPane().add(Panel2,"Center");this.setResizable(false);this.setTitle("计算器");this.addWindowListener(newjava.awt.event.WindowAdapter(){public void windowClosing(WindowEvent e){System.exit(0);}});}//end public Calculator1()public static void main(String[]args){Calculator mf=new Calculator();mf.setBounds(200,200,400,400);mf.show();}//end main()}//end public class Calculator1extends JFrame implements ActionListener</buttons.length();i++){<>。
Java计算器源代码(已成功运行)汇总
以下为代码:
importjavax.swing.*;
importjava.awt.*;
importjava.awt.event.*;
public class Calculator extends JFrame implements ActionListener
{
private booleandotExist, operated, equaled; //帮助运算的布尔变量
private double storedNumber; //目前的结果private char lastOperator; //表示上一运算符private JTextField operation; //结果栏
private JButton dot, plus, minus, multi, div, sqrt, equal, changePN, clear; //运算符
private JButton[] numbers; //数字
//构造者
public Calculator(
{
setTitle("Calculator";
//初始化变量
dotExist = false; //表示当前的数是否有小数点
operated = false; //表示任意运算符是否被按下equaled = false; //表示等号是否被按下storedNumber = 0;
else if (lastOperator == 's' storedNumber = Math.sqrt(currentNumber; else if (lastOperator == '=' && equaled storedNumber = currentNumber; operation.setText("" + storedNumber; operated = true; lastOperator = operator; } //快捷使用GridBagLayout的方法private void addComponent(GridBagLayout layout, Component component, int row, int col, int width, int height { GridBagConstraints constraints=new GridBagConstraints(; constraints.fill = GridBagConstraints.BOTH; constraints.insets = new Insets(10, 2, 10, 2; constraints.weightx = 100; constraints.weighty = 100; constraints.gridx = col; constraints.gridy = row; constraints.gridwidth = width; constraints.gridheight = height; layout.setConstraints(component, constraints;
计算器JAVA源代码
importjava.awt.*; //引入awt包importjavax.swing.*; //引入javax.swing包importjava.awt.event.*; //引入awt.event包public class TheCalculator extends WindowAdapter//程序框架继承自WindowAdapter类(窗体适配器){private JTextFieldJtext=new JTextField("");//程序初始化文本框的内容为空private JFrame f=new JFrame("计算器");//Jframe窗体名为“计算器”private String a=""; //声明变量类型private String b="";private String cal="";private boolean flag1=true; //声明变量flag1对象类型为布尔型private boolean flag2=false; //声明变量flag2对象类型为布尔型public void init() //初始化{String[] buttonValue = new String[]{"1","2","3","+","C","4","5","6","-","退格","7","8","9","*","1/x","0","+/-",".","/","="};Container contain = f.getContentPane();//初始化窗体JPanelJpan = new JPanel(); //实例化面板JButton[] Jbutton=new JButton[20]; //利用数组定义JBotton按钮contain.setLayout(new BorderLayout());Jpan.setLayout(new GridLayout(4,5)); //采用4行5列的网格布局Jtext.setHorizontalAlignment(JTextField.RIGHT);//文本域按右对齐的方式显示contain.add(Jtext,"North");//输入文字的面板整体靠北contain.add(Jpan);//添加Jpan到contain中Data num=new Data(); //实例化数据Result result=new Result(); //实例化计算结果Opertionopertion=new Opertion(); //实例化运算符Clear clear=new Clear(); //清零BackSpace backspace=new BackSpace(); //退格CountDown countdown=new CountDown(); //倒数Strains Strains=new Strains(); //相反数for(int i = 0;i <Jbutton.length;i++) //利用For循环添加按钮{Jbutton[i] = new JButton (buttonValue[i]);Jpan.add(Jbutton[i]); //依次将Jbutton数组中的数值添加到buttonValue的数组中if(i==3 || i==8 || i==13 ||i==18 ) //运算符所在位置Jbutton[i].addActionListener(opertion);if(i==0 || i==1 || i==2 || i==5 || i==6 || i==7|| i==10 || i==11 || i==12 || i==15 || i==17 )Jbutton[i].addActionListener(num);//数值所在位置if((i==3||i==4||i==8||i==9)||i==13||i==18||i==19)Jbutton[i].setForeground(new Color(255, 0, 0));elseJbutton[i].setForeground(new Color(0, 0, 255)); //控制按钮字体颜色}Jbutton[4].addActionListener(clear);Jbutton[9].addActionListener(backspace);Jbutton[14].addActionListener(countdown);Jbutton[16].addActionListener(Strains);Jbutton[19].addActionListener(result); //注册按钮事件监听器f.setSize(400,300); //设置窗体大小f.setVisible(true); //设置可见性f.addWindowListener( //采用匿名类实现窗口的正常关闭newWindowAdapter(){public void windowClosing(WindowEvent e) //响应窗口适配器{System.exit(0); //响应退出}});}class Data implements ActionListener //输入数据{public void actionPerformed(ActionEvent e){String m = Jtext.getText(); //m获取当前文本框内容String n = e.getActionCommand();//n获取按钮数值if(m.equals("")||m.equals("+")||m.equals("-")||m.equals("*")||m.equals("/")) Jtext.setText(n);else{if(flag2){Jtext.setText(n); //输出nflag2=false; //flag2的初始值为false}elseJtext.setText(m+n); //m、n合并,并输出,得到打一个要计算的数据}}}classOpertion implements ActionListener{public void actionPerformed(ActionEvent e){cal=e.getActionCommand();//运算符数值赋值给cal,并设置cal的初值为空if(flag1==true) //flag1初值为truea=Jtext.getText(); //计算的第一个数据保存在a字符串变量中Jtext.setText(cal); //运算符的数值复赋值给ca1flag1=false; //flag1赋值给false}}class Clear implements ActionListener //清零功能{public void actionPerformed(ActionEvent e){Jtext.setText("");}}class CountDown implements ActionListener //求倒数类{public void actionPerformed(ActionEvent e){ try{String s = e.getActionCommand(); //获取退格按钮的命令赋值给sString s1 = Jtext.getText(); //获得当前文本框内容赋值给s1if(s.equals("1/x"))s1 = new String (""+1/Double.parseDouble(s1));Jtext.setText(s1);}catch(Exception w){}}}class Strains implements ActionListener //求相反数类{public void actionPerformed(ActionEvent e){String s = e.getActionCommand(); //获取退格按钮的命令赋值给sString s1 = Jtext.getText(); //获得当前文本框内容赋值给s1if(s.equals("+/-"))s1=new String (""+(0-Double.parseDouble(s1)));Jtext.setText(s1);}}class BackSpace implements ActionListener //退格功能{public void actionPerformed(ActionEvent e){ try{String x = e.getActionCommand(); //获取退格按钮的命令赋值给xString y = Jtext.getText();//获得当前文本框内容赋值给yif(x.equals("退格"))y=new String (y.substring(0,y.length()-1)); //substring函数Jtext.setText(y);}catch(Exception w){}}}class Result implements ActionListener //计算并显示结果{public void actionPerformed(ActionEvent e){ try{double m; //将num1的数据类型定义Double型m=Double.parseDouble(a);//a强制转换成Double型,之后赋值给num1b=Jtext.getText(); //变量b得到当前的文本框内容double n; //将num2的数据类型定义Double型n=Double.parseDouble(b); //b强制转换成Double型,之后赋值给num2double result=0;if(n!=0){if(cal.equals("+"))result=m+n;if(cal.equals("-"))result=m-n;if(cal.equals("*"))result=m*n;String s1=Double.toString(result); //计算结果转换成字符串,输出至文本框Jtext.setText(s1);}if(cal.equals("/")){if(n==0) //num1是否等于0Jtext.setText("除数不能为0"); //文本框内显示“除数不能为0”else{result=m/n;String s1=Double.toString(result);Jtext.setText(s1);}}flag1=true; //将flag1赋值给trueflag2=true; //将flag2赋值给true}catch(Exception w){}}}public static void main(String[] args){TheCalculator count=new TheCalculator();count.init();}}。
java编写计算器源代码
计算器的制作import java.awt.*;import java.awt.event.*;class ComputerExe extends Frame implements ActionListener {Button b1,b2,b3,b4;TextField t1,t2,t3;Label l1,l2;public static void main(String[] args)//程序入口{new ComputerExe();//创建本窗体对象}ComputerExe()//构造方法{super("四则运算");setBounds(100,100,300,200);setVisible(true);b1=new Button("加");b2=new Button("减");b3=new Button("乘");b4=new Button("除");t1=new TextField(15);t2=new TextField(15);t3=new TextField(15);l1=new Label("");l2=new Label("=");l1.setBackground(Color.yellow);l1.setForeground(Color.red);l2.setBackground(Color.yellow);l2.setForeground(Color.red);t3.setEditable(false);setLayout(new FlowLayout());//更改窗体框架的布局add(t1);add(l1);add(t2);add(l2);add(t3);add(b1);add(b2);add(b3);add(b4);setVisible(true);b1.addActionListener(this);b2.addActionListener(this);b3.addActionListener(this);b4.addActionListener(this);}//构造方法结束public void actionPerformed(ActionEvent e) { double n1,n2,n3;if(e.getSource()==b1){try{n1=Double.parseDouble(t1.getText());n2=Double.parseDouble(t2.getText());n3=n1+n2;t3.setText(String.valueOf(n3));l1.setText("+");}catch(NumberFormatException w){t3.setText("操作数应该为数字!");}}if(e.getSource()==b2){try{n1=Double.parseDouble(t1.getText());n2=Double.parseDouble(t2.getText());n3=n1-n2;t3.setText(String.valueOf(n3));l1.setText("-");}catch(NumberFormatException w){t3.setText("操作数应该为数字!");}}if(e.getSource()==b3){try{n1=Double.parseDouble(t1.getText());n2=Double.parseDouble(t2.getText());n3=n1*n2;t3.setText(String.valueOf(n3));l1.setText("*");}catch(NumberFormatException w){t3.setText("操作数应该为数字!");}}if(e.getSource()==b4){try{n1=Double.parseDouble(t1.getText());n2=Double.parseDouble(t2.getText());n3=n1/n2;t3.setText(String.valueOf(n3));l1.setText("/");}catch(NumberFormatException w){t3.setText("操作数应该为数字!");}}}}//类结束。
JAVA编写的计算器源代码
JAVA编写的计算器源代码// Calculator.javaimport javax.swing.*; // 引入swing库import java.awt.*; // 引入awt库import java.awt.event.*; // 引入awt.event库public class Calculator extends JFrame implements ActionListener//定义按钮private JButton zero;private JButton one;private JButton two;private JButton three;private JButton four;private JButton five;private JButton six;private JButton seven;private JButton eight;private JButton nine;private JButton point;private JButton equal; private JButton plus; private JButton minus; private JButton multiply; private JButton divide; private JButton backspace; private JButton ac;private JButton ce;private JButton sqrt; private JButton sqr;private JButton plus_minus; private JButton delete; private JButton sin;private JButton cos;private JButton tan;private JButton log;private JButton nfactorial; private JButton cubic; private JButton coln;private JButton factorial;//定义文本框private JTextField resulttext;// 定义boolean变量boolean clrdisp = true; // 昵称确定是否清除计算器显示boolean isCalculate = false; // 是否可以执行计算// 定义String变量,用于存储操作符String optr;//定义存储第一个操作数double num1;//初始化构造函数public Calculato//设置布局setLayout(new BorderLayout();//创建面板JPanel northPanel = new JPanel(;JPanel centerPanel = new JPanel(;JPanel southPanel = new JPanel(;//设置面板布局northPanel.setLayout(new FlowLayout(); centerPanel.setLayout(new GridLayout(4, 5)); southPanel.setLayout(new FlowLayout();//设置计算器显示resulttext = new JTextField(28); northPanel.add(resulttext);resulttext.setEditable(false);//初始化按钮zero = new JButton("0");one = new JButton("1");two = new JButton("2");three = new JButton("3");four = new JButton("4");five = new JButton("5");six = new JButton("6");seven = new JButton("7");eight = new JButton("8");nine = new JButton("9");point = new JButton(".");equal = new JButton("=");plus = new JButton("+");minus = new JButton("-"); multiply = new JButton("*"); divide = new JButton("/"); backspace = new JButton("<-"); ac = new JButton("AC");ce = new JButton("CE");sqrt = new JButton("sqrt");sqr = new JButton("sqr");plus_minus = new JButton("+/-");。
JAVA编写的计算器源代码(word文档良心出品)
package jsq;import java.awt.Color;import java.awt.GridLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.WindowEvent;import java.awt.event.WindowListener;import javax.swing.ImageIcon;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JMenu;import javax.swing.JMenuBar;import javax.swing.JMenuItem;import javax.swing.JOptionPane;import javax.swing.JPanel;import javax.swing.JTextField;import javax.swing.UIManager;public class Test implements ActionListener {/****/JFrame f = new JFrame();JTextField tf = new JTextField("0.");JMenuBar bar=new JMenuBar();JMenu menuEdit=new JMenu("编辑(E)");JMenu menuView=new JMenu("查看(V)");JMenu menuHelp=new JMenu("帮助(H)");JMenuItem menuEditCopy=new JMenuItem("复制(C)");JMenuItem menuEditPaste=new JMenuItem("粘贴(V)");JMenuItem menuHelpAbout = new JMenuItem("关于计算器(A)");JPanel panel0 = new JPanel();JPanel panel2 = new JPanel();JPanel panel = new JPanel();JPanel panel3 = new JPanel();JPanel panel4 = new JPanel();JPanel panel5 = new JPanel();JButton btBk = new JButton(" Backspace"); JButton btCe = new JButton("Ce");JButton btCl = new JButton("C");JButton bt7 = new JButton("7");JButton bt8 = new JButton("8");JButton bt9 = new JButton("9");JButton btDiv = new JButton("/");JButton btSqrt = new JButton("sqrt");JButton bt4 = new JButton("4");JButton bt5 = new JButton("5");JButton bt6 = new JButton("6");JButton btMult = new JButton("*"); JButton btMol = new JButton(" % ");JButton bt1 = new JButton("1");JButton bt2 = new JButton("2");JButton bt3 = new JButton("3");JButton btMinu = new JButton("-"); JButton btCoun = new JButton(" 1/x");JButton bt0 = new JButton("0");JButton btPoint = new JButton("."); JButton btEqual = new JButton("="); JButton btAdd = new JButton("+");JButton btSign = new JButton(" +/-");/***@param args*/public void init(){f.add(panel0);f.add(tf,"North");f.setJMenuBar(bar);bar.add(menuEdit);bar.add(menuView);bar.add(menuHelp);menuEdit.add(menuEditCopy);menuEdit.add(menuEditPaste);menuHelp.add(menuHelpAbout);tf.setEditable(false);//不可编辑tf.setHorizontalAlignment(JTextField.RIGHT);//从右侧输入数据panel0.add(panel2);panel0.add(panel);panel0.add(panel3);panel0.add(panel4);panel0.add(panel5);panel2.setLayout(new GridLayout(1,4));panel2.add(btBk);panel2.add(btCe);panel2.add(btCl);panel.setLayout(new GridLayout(1,5));panel.add(bt7);panel.add(bt8);panel.add(bt9);panel.add(btDiv);panel.add(btSqrt);//根号panel3.setLayout(new GridLayout(1,5));panel3.add(bt4);panel3.add(bt5);panel3.add(bt6);panel3.add(btMult);panel3.add(btMol);//百分号panel4.setLayout(new GridLayout(1,5));panel4.add(bt1);panel4.add(bt2);panel4.add(bt3);panel4.add(btMinu);panel4.add(btCoun);//倒数panel5.setLayout(new GridLayout(1,5));panel5.add(bt0);panel5.add(btPoint);panel5.add(btAdd);panel5.add(btEqual);panel5.add(btSign);//正负符号btBk.setForeground(new Color(255, 0, 0)); btCe.setForeground(new Color(255, 0, 0)); btCl.setForeground(new Color(255, 0, 0)); btAdd.setForeground(new Color(255, 0, 0)); btMult.setForeground(new Color(255, 0, 0)); btDiv.setForeground(new Color(255, 0, 0)); btMinu.setForeground(new Color(255, 0, 0)); btEqual.setForeground(new Color(255, 0, 0));bt0.setForeground(new Color(0,0,255));bt1.setForeground(new Color(0, 0, 255));bt2.setForeground(new Color(0,0,255));bt3.setForeground(new Color(0,0,255));bt4.setForeground(new Color(0,0,255));bt5.setForeground(new Color(0,0,255));bt6.setForeground(new Color(0,0,255));bt7.setForeground(new Color(0,0,255));bt8.setForeground(new Color(0,0,255));bt9.setForeground(new Color(0,0,255)); btSqrt.setForeground(new Color(0,0,255)); btMol.setForeground(new Color(0,0,255)); btCoun.setForeground(new Color(0,0,255)); btSign.setForeground(new Color(0,0,255));//注册监听bt1.addActionListener(this);bt2.addActionListener(this);bt3.addActionListener(this);bt4.addActionListener(this);bt5.addActionListener(this);bt6.addActionListener(this);bt7.addActionListener(this);bt8.addActionListener(this);bt9.addActionListener(this);bt0.addActionListener(this);btAdd.addActionListener(this);btMinu.addActionListener(this);btMult.addActionListener(this);btDiv.addActionListener(this);btEqual.addActionListener(this);btPoint.addActionListener(this);btSqrt.addActionListener(this);btMol.addActionListener(this);btCoun.addActionListener(this);btSign.addActionListener(this);btBk.addActionListener(this);btCe.addActionListener(this);btCl.addActionListener(this);menuEditCopy.addActionListener(this);menuEditPaste.addActionListener(this);menuHelpAbout.addActionListener(this);f.addWindowListener(new MyWinLis());f.setTitle("计算器");f.setSize(295,240);f.setResizable(false);//不能改变窗体大小f.setVisible(true);}String foreNum=null;String currOpr=null;String currNum=null;boolean i = true;String copy;//复制public void actionPerformed(ActionEvent e) {// TODO自动生成方法存根Object obj=e.getSource();//输入数字if(obj==bt1||obj==bt2||obj==bt3||obj==bt4||obj==bt5||obj==bt6||obj==bt7||obj== bt8||obj==bt9||obj==bt0){if(i==true)tf.setText(e.getActionCommand());elsetf.setText(tf.getText()+e.getActionCommand());i = false;}//小数点else if(obj==btPoint){if(i==false)tf.setText(tf.getText()+'.');}//实现开根号else if(obj==btSqrt){if(tf.getText().charAt(0)=='-'){tf.setText("函数输入无效");}elsetf.setText(Double.toString(ng.Math.sqrt(Double. parseDouble(tf.getText()))));i = true;}//实现倒数else if(obj==btCoun){if (tf.getText().charAt(0) == '0') {tf.setText("零不能求倒数");i = true;}else {String s = Double.toString(1 / Double.parseDouble(tf.getText()));foreNum = tf.getText();tf.setText(s);i = true;}}//实现+/-符号else if (obj == btSign) {boolean isNumber = true;String s = tf.getText();for (int m = 0; m< s.length(); m++)if (! (s.charAt(m) >= '0' && s.charAt(m) <='9' || s.charAt(m) =='.'||s.charAt(m) == '-')) {break;}if (isNumber == true) {//如果当前字符串首字母有-号,代表现在是个负数,再按下时,则将首符号去掉if (s.charAt(0) == '-') {tf.setText("");for (int m = 1; m< s.length(); m++) {char a = s.charAt(m);tf.setText(tf.getText() + a);}}//如果当前字符串第一个字符不是符号,则添加一个符号在首字母处elsetf.setText('-' + s);}}//实现%功能else if(obj==btMol){boolean isNumber = true;if(isNumber==true)tf.setText(String.valueOf(Double.parseDouble(tf.getText())/100));elsetf.setText("错误");}//实现符号运算else if(obj==btAdd||obj==btMinu||obj==btDiv||obj==btMult){if(i==false){currNum=tf.getText();if(currOpr=="+")tf.setText(String.valueOf(Double.parseDouble(foreNum)+Double.parseDouble(currN um)));else if(currOpr=="-")tf.setText(String.valueOf(Double.parseDouble(foreNum)-Double.parseDouble(currN um)));else if(currOpr=="*")tf.setText(String.valueOf(Double.parseDouble(foreNum)*Double.parseDouble(currN um)));else if(currOpr=="/"){if (Double.parseDouble(tf.getText()) == 0)tf.setText("除数不能为零");elsetf.setText(String.valueOf(Double.parseDouble(foreNum)/Double.parseDouble(currNum))) ;}}foreNum=tf.getText();tf.setText("");currOpr=e.getActionCommand();i = false;}//实现等号else if(obj==btEqual){currNum=tf.getText();if(currOpr=="+")tf.setText(String.valueOf(Double.parseDouble(foreNum)+Double.parseDouble(currN um)));else if(currOpr=="-")tf.setText(String.valueOf(Double.parseDouble(foreNum)-Double.parseDouble(currN um)));else if(currOpr=="*")tf.setText(String.valueOf(Double.parseDouble(foreNum)*Double.parseDouble(currN um)));else if(currOpr=="/"){if (Double.parseDouble(tf.getText()) == 0)tf.setText("除数不能为零");elsetf.setText(String.valueOf(Double.parseDouble(foreNum)/Double.parseDouble(currN um)));}currOpr=e.getActionCommand();i = true;}//实现Backspace功能else if(obj==btBk){String s = tf.getText();tf.setText("");for (int m = 0;m <s.length() - 1; m++) {char a = s.charAt(m);tf.setText(tf.getText() + a);i = true;}}//实现Ce功能else if (obj == btCe) {tf.setText("0.");}//实现C功能else if (obj == btCl) {foreNum=currNum="";tf.setText("0.");}//实现复制else if(obj==menuEditCopy){copy=tf.getText();}//实现粘贴else if (obj == menuEditPaste) {tf.setText(copy);}//实现帮助主题else if(obj == menuHelpAbout){ImageIcon icon = new ImageIcon("src//Icons//about1.jpg");JLabel label = new JLabel(icon);JOptionPane.showMessageDialog(f,label,"帮助主题",JOptionPane.PLAIN_MESSAGE);}}public static void main(String[] args) {// TODO自动生成方法存根try{UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());//UIManager统一管理}catch(Exception e) {e.printStackTrace();}Test t = new Test();t.init();}}class MyWinLis implements WindowListener{public void windowActivated(WindowEvent arg0) {// TODO自动生成方法存根}public void windowClosed(WindowEvent arg0) { // TODO自动生成方法存根}public void windowClosing(WindowEvent arg0) { // TODO自动生成方法存根System.exit(0);}public void windowDeactivated(WindowEvent arg0) { // TODO自动生成方法存根}public void windowDeiconified(WindowEvent arg0) { // TODO自动生成方法存根}public void windowIconified(WindowEvent arg0) { // TODO自动生成方法存根}public void windowOpened(WindowEvent arg0) { // TODO自动生成方法存根}}。
java语言写的计算器源代码附解析
//把代码改成Calc.java编译运行,完整版计算器,最下面是计算器界面import java.awt.*;import java.awt.event.*;public class Calc extends WindowAdapter implements ActionListener, MouseListener{Color cMoveOut=new Color(240 ,240 ,240);Color cMoveIn =new Color( 255,255,55);//状态变量boolean clicked=true;//判断是否单击了小数点boolean clear=true;//判断是否单击了符号位double previous;//记录第一个操作数double next;//记录第二个操作数String fuhao;//记录符号位int first=1;//标记是否开始一次新的运算过程Frame f;Panel p1,p2;TextField tf;Font fnt;Button b1,b2,b3,b4,b5,b6,b7,b8,b9,b0;Button bDiv,bSqrt,bMulti,bMinus,bPercent,bPlus,bReciprocal,bEqual,bDot,bNegative,bBack;Button bPingFang , bDaoShu , bSin, bCos ,bTan;Button bC;GridLayout p2Layout;public void display(){f=new Frame("计算器");f.setSize(280,213);f.setLocation(200,200);f.setBackground(Color.LIGHT_GRAY);f.setResizable(false);p1=new Panel(new FlowLayout());tf=new TextField(35);tf.setText("0.");tf.setEditable(false);p1.add(tf);f.add(p1,BorderLayout.NORTH);p2Layout=new GridLayout(5,5,5,4);p2=new Panel(p2Layout);f.add(p2,BorderLayout.CENTER);fnt=new Font("Serief",Font.BOLD,20);b1=new Button("1");b1.setFont(fnt);b2=new Button("2");b2.setFont(fnt);b3=new Button("3");b3.setFont(fnt);b4=new Button("4");b4.setFont(fnt);b5=new Button("5");b5.setFont(fnt);b6=new Button("6");b6.setFont(fnt);b7=new Button("7");b7.setFont(fnt);b8=new Button("8");b8.setFont(fnt);b7.setFont(fnt);b9=new Button("9");b9.setFont(fnt);b0=new Button("0");b0.setFont(fnt);b9.setFont(fnt);bPingFang=new Button("^2"); bPingFang.setFont(fnt); bDaoShu=new Button("1/X"); bDaoShu.setFont(fnt);bSin=new Button("sin");bSin.setFont(fnt);bCos=new Button("cos"); bCos.setFont(fnt);bTan=new Button("tan"); bTan.setFont(fnt);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); bBack=new Button("Back");//退格bBack.setFont(fnt);bC=new Button("C");//清空bC.setFont(fnt);bDiv=new Button("/");bDiv.setFont(fnt);bSqrt=new Button("sqrt"); bSqrt.setFont(fnt);bMulti=new Button("*"); bMulti.setFont(fnt);bMinus=new Button("-"); bMinus.setFont(fnt);bPercent=new Button("%"); bPercent.setFont(fnt);bPlus=new Button("+"); bPlus.setFont(fnt);bEqual=new Button("="); bEqual.setFont(fnt);bDot=new Button(".");bDot.setFont(fnt);bNegative=new Button("+/-"); bNegative.setFont(fnt); bBack.addActionListener(this);bC.addActionListener(this); bDiv.addActionListener(this); bSqrt.addActionListener(this); bPingFang.addActionListener(this); bPercent.addActionListener(this); bDaoShu.addActionListener(this); bMulti.addActionListener(this); bPlus.addActionListener(this); bMinus.addActionListener(this); bMulti.addActionListener(this); bDiv.addActionListener(this); bSin.addActionListener(this); bCos.addActionListener(this); bTan.addActionListener(this); bEqual.addActionListener(this); bDot.addActionListener(this); bNegative.addActionListener(this); bSqrt.addMouseListener(this); bPingFang.addMouseListener(this); bPercent.addMouseListener(this); bC.addMouseListener(this); bBack.addMouseListener(this);b7.addMouseListener(this);b8.addMouseListener(this);b9.addMouseListener(this); bDiv.addMouseListener(this); bDaoShu.addMouseListener(this); b4.addMouseListener(this);b5.addMouseListener(this);b6.addMouseListener(this); bMulti.addMouseListener(this); bSin.addMouseListener(this);b1.addMouseListener(this);b2.addMouseListener(this);b3.addMouseListener(this); bMinus.addMouseListener(this); bCos.addMouseListener(this);b0.addMouseListener(this); bDot.addMouseListener(this); bEqual.addMouseListener(this); bPlus.addMouseListener(this); bTan.addMouseListener(this);p2.add(bSqrt);p2.add(bPingFang);p2.add(bPercent);p2.add(bC);p2.add(bBack);p2.add(b7);p2.add(b8);p2.add(b9);p2.add(bDiv);p2.add(bDaoShu);p2.add(b4);p2.add(b5);p2.add(b6);p2.add(bMulti);p2.add(bSin);p2.add(b1);p2.add(b2);p2.add(b3);p2.add(bMinus);p2.add(bCos);p2.add(b0);p2.add(bDot);p2.add(bEqual);p2.add(bPlus);p2.add(bTan);f.setV isible(true);f.addWindowListener(this);}public void actionPerformed(ActionEvent e) {if (first ==1)tf.setText("");first=0;Object temp=e.getSource();//退格if (temp== bBack){String s=tf.getText();tf.setText("");for (int i=0;i<s.length()-1;i++){char a=s.charAt(i);tf.setText(tf.getText()+a);}}//清零if (temp==bC){tf.setText("0.");clear=true;first=1;}if (temp==b0){//判断是否单击了符号位if (clear==false)tf.setText("");tf.setText(tf.getText()+"0");}if (temp==b1){if (clear==false)tf.setText("");tf.setText(tf.getText()+"1");clear=true;}if (temp==b2){if (clear==false)tf.setText("");tf.setText(tf.getText()+"2");clear=true;}if (temp==b3){if (clear==false)tf.setText("");tf.setText(tf.getText()+"3");clear=true;}if (temp==b4){if (clear==false)tf.setText("");tf.setText(tf.getText()+"4");clear=true;}if (temp==b5){if (clear==false)tf.setText("");tf.setText(tf.getText()+"5");clear=true;}if (temp==b6){if (clear==false)tf.setText("");tf.setText(tf.getText()+"6");clear=true;}if (temp==b7){if (clear==false)tf.setText("");tf.setText(tf.getText()+"7");clear=true;}if (temp==b8){if (clear==false)tf.setText("");tf.setText(tf.getText()+"8");clear=true;}if (temp==b9){if (clear==false)tf.setText("");tf.setText(tf.getText()+"9");clear=true;}//判断是否含有小数点if (temp == bDot){clicked=true;for (int i=0;i<tf.getText().length();i++)if ('.'==tf.getText().charAt(i)){clicked = false;break;}if (clicked == true){tf.setText(tf.getText()+".");clear=true;}}//bSqrtif(temp == bSqrt){tf.setText( Math.sqrt( Double.parseDouble(tf.getText())) + "" );clear=false;}//bPingFangif(temp == bPingFang ){tf.setText( Math.pow( Double.parseDouble(tf.getText() ), 2 ) + "" );clear=false;}//倒数if(temp == bDaoShu){tf.setText( 1 / Double.parseDouble(tf.getText()) + "" );clear =false;}//Sinif(temp == bSin){tf.setText( Math.sin( Math.toRadians( Double.parseDouble( tf.getText() ) ) ) + "" );clear =false;}//Cosif(temp == bCos){tf.setText( Math.cos( Math.toRadians( Double.parseDouble( tf.getText() ) ) ) + "" );clear =false;}//tanif(temp == bTan){tf.setText( Math.tan( Math.toRadians( Double.parseDouble( tf.getText() ) ) ) + "");clear =false;}//加法运算if (temp==bPlus){previous=Double.parseDouble(tf.getText());fuhao="+";clear=false;//System.out.print("+");}//减法运算if (temp == bMinus){previous=Double.parseDouble(tf.getText());fuhao="-";clear=false;}//乘法运算if (temp == bMulti){previous=Double.parseDouble(tf.getText());fuhao="*";clear=false;}//除法运算bDivif (temp == bDiv){previous=Double.parseDouble(tf.getText());fuhao="/";clear=false;}//求余数if(temp == bPercent){previous=Double.parseDouble( tf.getText());fuhao="%";clear=false;}//等于if (temp==bEqual){try{next = Double.parseDouble(tf.getText());tf.setText("");if (fuhao =="+")tf.setText(previous + next +"");if(fuhao == "-")tf.setText(previous - next +"");if(fuhao == "*")tf.setText(previous * next +"");if(fuhao == "/")tf.setText(previous / next +"");if(fuhao == "%")tf.setText(previous % next +"");clear=false;}catch(Exception ex){tf.setText("请检查输入的数据:" + ex.getMessage()) ;clear=false;}}}public void mouseEntered(MouseEvent e){Object temp= e.getSource();if(temp==bPingFang){//System.out.println( bBack.getBackground() );bPingFang.setBackground(cMoveIn);}if(temp==bSqrt){bSqrt.setBackground(cMoveIn);}if(temp==bPercent){bPercent.setBackground(cMoveIn);}if(temp==bC){bC.setBackground(cMoveIn);}if(temp==bBack){bBack.setBackground(cMoveIn);}if(temp==b7){b7.setBackground(cMoveIn);}if(temp==b8){b8.setBackground(cMoveIn);}if(temp==b9){b9.setBackground(cMoveIn);}if(temp==bDiv){bDiv.setBackground(cMoveIn);}if(temp==bDaoShu){bDaoShu.setBackground(cMoveIn); }if(temp==b4){b4.setBackground(cMoveIn);}if(temp==b5){b5.setBackground(cMoveIn);}if(temp==b6){b6.setBackground(cMoveIn);}if(temp==bMulti){bMulti.setBackground(cMoveIn); }if(temp==bSin){bSin.setBackground(cMoveIn);}if(temp==b1){b1.setBackground(cMoveIn);}if(temp==b2){b2.setBackground(cMoveIn);}if(temp==b3){b3.setBackground(cMoveIn);}if(temp==bMinus){bMinus.setBackground(cMoveIn); }if(temp==bCos){bCos.setBackground(cMoveIn);}if(temp==b0){b0.setBackground(cMoveIn);}if(temp==bDot){bDot.setBackground(cMoveIn);}if(temp==bEqual){bEqual.setBackground(cMoveIn);}if(temp==bPlus){bPlus.setBackground(cMoveIn);}if(temp==bTan){bTan.setBackground(cMoveIn);}}public void mouseExited(MouseEvent e) {Object temp= e.getSource();if(temp==bPingFang){//System.out.println( bBack.getBackground() );bPingFang.setBackground(cMoveOut);}if(temp==bSqrt){bSqrt.setBackground(cMoveOut);}if(temp==bPercent){bPercent.setBackground(cMoveOut);}if(temp==bC){bC.setBackground(cMoveOut);}if(temp==bBack){bBack.setBackground(cMoveOut);}if(temp==b7){b7.setBackground(cMoveOut);}if(temp==b8){b8.setBackground(cMoveOut);}if(temp==b9){b9.setBackground(cMoveOut);}if(temp==bDiv){bDiv.setBackground(cMoveOut);}if(temp==bDaoShu){bDaoShu.setBackground(cMoveOut); }if(temp==b4){b4.setBackground(cMoveOut);}if(temp==b5){b5.setBackground(cMoveOut);}if(temp==b6){b6.setBackground(cMoveOut);}if(temp==bMulti){bMulti.setBackground(cMoveOut); }if(temp==bSin){bSin.setBackground(cMoveOut);}if(temp==b1){b1.setBackground(cMoveOut);}if(temp==b2){b2.setBackground(cMoveOut);}if(temp==b3){b3.setBackground(cMoveOut);}if(temp==bMinus){bMinus.setBackground(cMoveOut); }if(temp==bCos){bCos.setBackground(cMoveOut);}if(temp==b0){b0.setBackground(cMoveOut);}if(temp==bDot){bDot.setBackground(cMoveOut);}if(temp==bEqual){bEqual.setBackground(cMoveOut);}if(temp==bPlus){bPlus.setBackground(cMoveOut);}if(temp==bTan){bTan.setBackground(cMoveOut);}}public static void main(String args[]){Calc frame=new Calc();frame.display();}public void windowClosing(WindowEvent e){System.exit(0);}public void mouseClicked(MouseEvent arg0) {}public void mousePressed(MouseEvent arg0) {}public void mouseReleased(MouseEvent arg0) { }}。
计算器(JAVA)源代码
//定义计算的类import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.JTextField;public class Caculate implements ActionListener { //设置属性private String data;private JTextField text;private String result = "0";private boolean start_new = false;private double last_value = 0;private String ope = "";private double value = 0;public String getResult (){return result;}//定义一个构造方法public Caculate(JTextField text){this.text = text;}@Override//按钮事件处理public void actionPerformed(ActionEvent cal) { // TODO Auto-generated method stubdata = cal.getActionCommand();data = data.trim();if("0123456789".indexOf(data) != -1){numButton(data);}else if (".".indexOf(data) != -1){dotButton(data);}else if ("+-*/".indexOf(data) != -1){operateButton(data);}else if ("=".indexOf(data)!=-1){equalButton();}//System.out.println(data);System.out.println(result);text.setText(result);}//计算程序private void numButton(String da){if(!start_new){result = result + da;}else{result = da;}while (result.startsWith("0")&&!result.startsWith("0.")&&result.length()>0){ result = result.substring(1);}start_new = false;}private void dotButton(String da){if(da.indexOf(".")!= -1){result = result + da;}}private void operateButton(String da){if(result.length()>0){last_value = Double.parseDouble(result);ope = da;start_new = true;}}private void equalButton(){value = Double.parseDouble(result);if(ope.equals("+")){result = String.valueOf(last_value + value);}else if(ope.equals("-")){result = String.valueOf(last_value - value);}else if(ope.equals("*")){result = String.valueOf(last_value * value);}else if(ope.equals("/")){if(value == 0){result = "ERROR";}else{result = String.valueOf(last_value / value);}}// 去掉结尾的“.0000...”if (result.matches(".+\\.0+")) {result = result.substring(0, stIndexOf("."));}// 设置状态start_new = true;ope = "";}}import javax.swing.JTextField;public class Culator {private static final String String = null;JTextField op;private String re;/*** @param args*/public static void main(String[] args) {Culator cul = new Culator();cul.init();// TODO Auto-generated method stub}public void init(){javax.swing.JFrame frame = new javax.swing.JFrame(); frame.setTitle("计算器");java.awt.FlowLayout f1= new java.awt.FlowLayout();frame.setLayout(f1);javax.swing.JMenuBar cai = createMB();frame.setJMenuBar(cai);javax.swing.JButton mc = new javax.swing.JButton("MC");op= new javax.swing.JTextField("0",25);//设置数字从右边开始显示op.setHorizontalAlignment(JTextField.RIGHT);//设置按钮javax.swing.JButton mr = new javax.swing.JButton("MR"); javax.swing.JButton ms = new javax.swing.JButton("MS"); javax.swing.JButton mp = new javax.swing.JButton("M+"); javax.swing.JButton mm = new javax.swing.JButton("M-"); javax.swing.JButton delete = new javax.swing.JButton(" ←"); javax.swing.JButton ce = new javax.swing.JButton("CE "); javax.swing.JButton c = new javax.swing.JButton(" C "); javax.swing.JButton pm = new javax.swing.JButton(" ± "); javax.swing.JButton r = new javax.swing.JButton(" √"); javax.swing.JButton seven = new javax.swing.JButton(" 7 "); javax.swing.JButton eight = new javax.swing.JButton(" 8 "); javax.swing.JButton nine = new javax.swing.JButton(" 9 ");javax.swing.JButton under = new javax.swing.JButton(" / ");javax.swing.JButton percent = new javax.swing.JButton(" % ");javax.swing.JButton four = new javax.swing.JButton(" 4 ");javax.swing.JButton five = new javax.swing.JButton(" 5 ");javax.swing.JButton six = new javax.swing.JButton(" 6 ");javax.swing.JButton and = new javax.swing.JButton(" * ");javax.swing.JButton ds = new javax.swing.JButton("1/x");javax.swing.JButton one = new javax.swing.JButton(" 1 ");javax.swing.JButton two = new javax.swing.JButton(" 2 ");javax.swing.JButton three = new javax.swing.JButton(" 3 ");javax.swing.JButton m = new javax.swing.JButton(" - ");javax.swing.JButton equal = new javax.swing.JButton(" = ");javax.swing.JButton zero = new javax.swing.JButton(" 0 ");javax.swing.JButton dot = new javax.swing.JButton(" . ");javax.swing.JButton plus = new javax.swing.JButton(" + ");//添加按钮frame.add(op);frame.add(mc);frame.add(mr);frame.add(ms);frame.add(mp);frame.add(mm);frame.add(delete);frame.add(ce);frame.add(c);frame.add(pm);frame.add(r);frame.add(seven);frame.add(eight);frame.add(nine);frame.add(under);frame.add(percent);frame.add(four);frame.add(five);frame.add(six);frame.add(and);frame.add(ds);frame.add(one);frame.add(two);frame.add(three);frame.add(m);frame.add(equal);frame.add(zero);frame.add(dot);frame.add(plus);frame.setSize(290,300);//实例化一个Caculate类Caculate cal = new Caculate(op);//增加监听op.addActionListener(cal);mc.addActionListener(cal);mr.addActionListener(cal);ms.addActionListener(cal);mp.addActionListener(cal);mm.addActionListener(cal);delete.addActionListener(cal);ce.addActionListener(cal);c.addActionListener(cal);pm.addActionListener(cal);r.addActionListener(cal);seven.addActionListener(cal);eight.addActionListener(cal);nine.addActionListener(cal);under.addActionListener(cal); percent.addActionListener(cal);four.addActionListener(cal);five.addActionListener(cal);six.addActionListener(cal);and.addActionListener(cal);ds.addActionListener(cal);one.addActionListener(cal);two.addActionListener(cal);three.addActionListener(cal);m.addActionListener(cal);equal.addActionListener(cal);zero.addActionListener(cal);dot.addActionListener(cal);plus.addActionListener(cal);frame.setDefaultCloseOperation(3); frame.setResizable(false);frame.setVisible(true);}//创建一个设置TextField窗口容的函数//public void setOp(String re){// op.setText(re);//}//创建一个常带有菜单的菜单条,就加到JFrame上显示private javax.swing.JMenuBar createMB(){//创建菜单条javax.swing.JMenuBar mb = new javax.swing.JMenuBar();//创建查看菜单javax.swing.JMenu view = new javax.swing.JMenu("查看(V)");//创建菜单项javax.swing.JMenuItem biaozhun = new javax.swing.JMenuItem("标准型"); javax.swing.JMenuItem kexue = new javax.swing.JMenuItem("科学型"); javax.swing.JMenuItem chengxu = new javax.swing.JMenuItem("程序员"); javax.swing.JMenuItem tongji = new javax.swing.JMenuItem("统计信息"); javax.swing.JMenuItem history = new javax.swing.JMenuItem("历史");//将菜单项添加到菜单上view.add(biaozhun);view.add(kexue);view.add(chengxu);view.add(tongji);view.add(history);//创建编辑菜单javax.swing.JMenu operation = new javax.swing.JMenu("编辑(O)");//创建菜单项javax.swing.JMenuItem copy = new javax.swing.JMenuItem("复制"); javax.swing.JMenuItem paste = new javax.swing.JMenuItem("黏贴"); javax.swing.JMenuItem hr = new javax.swing.JMenuItem("历史记录");//将菜单项添加到菜单上operation.add(copy);operation.add(paste);operation.add(hr);//创建帮助菜单javax.swing.JMenu help = new javax.swing.JMenu("帮助(H)");//创建帮助菜单项javax.swing.JMenuItem vh = new javax.swing.JMenuItem("查看帮助"); javax.swing.JMenuItem about = new javax.swing.JMenuItem("关于计算器"); //将菜单项添加到菜单上help.add(vh);help.add(about);//加上一个分隔条help.addSeparator();//将菜单添加到菜单条上mb.add(view);mb.add(operation);mb.add(help);return mb;} }。
Java计算器源码
计算器本计算器有显示过程和不显示过程两种功能,其中不显示过程为普通计算器,类似于windows自带的计算器;显示过程的,可以显示预算过程,其中包含所需应用的部分函数,以及格式化功能(最左上角,第一个键格式化,然后输入需要格式化的数位,然后点第二个数,显示格式化结果),当一次运算结束后,会在右边自动显示运算过程,并且运算过程处有保存,复制粘贴清除功能。
代码如下:主类:import ZF.*;public class JiSuanQi {public static void main(String[] args) {Calculator c = new Calculator("计算器");}}包ZF中的类:Calculator类package ZF;/*** 计算器布局界面*/import java.io.*;import java.awt.*;import javax.swing.*;import java.awt.event.*;public class Calculator extends JFrame implements ActionListener {static int xg = 1;// 用于判断是否显示过程,初始状态为显示JSplitPane jsp1, jsp2, jsp3;static JTextField jtf;// 文本框static JTextArea jta;// 保存等的历史文本区public static String zc;// 用来暂时存储数字,实现第一个菜单选项JScrollPane JS;// 专门用于给文本区提供滚动条public static FileDialog load, save;// 声明引入对话框BufferedReader in;//FileReader reader;//JP1 jp1;JP2 jp2;JP3 jp3;JP4 jp4;JP5 jp5;// 菜单条JMenuBar mb;JMenu m0, m1, m2;JMenuItem m01, m02, m03, m04, m11, m12, m21, m22;public Calculator(String s) {super(s);Container con = getContentPane();// 桌面jp1 = new JP1();jp2 = new JP2();jp3 = new JP3();jp4 = new JP4();jp5 = new JP5();jta = new JTextArea();jta.setEditable(false);JS = new JScrollPane(jta);jsp1 = new JSplitPane(JSplitPane.VERTICAL_SPLIT, false, jp1, jp2);jsp2 = new JSplitPane(JSplitPane.VERTICAL_SPLIT, false, jp3, JS);jsp3 = new JSplitPane(JSplitPane.VERTICAL_SPLIT, false, jp4, jp5);jtf = new JTextField();jtf.setText(String.valueOf(0));jtf.setEditable(false);jtf.setBackground(Color.white);load = new FileDialog(this, "读取历史运算过程", FileDialog.LOAD);load.setVisible(false);load.addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent e) {load.setVisible(false);}});save = new FileDialog(this, "保存历史运算过程", FileDialog.SAVE); save.setVisible(false);save.addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent e) {save.setVisible(false);}});// 菜单条mb = new JMenuBar();m0 = new JMenu("编辑");m1 = new JMenu("查看");m2 = new JMenu("帮助");m01 = new JMenuItem("复制");m02 = new JMenuItem("粘贴");m03 = new JMenuItem("读取");m04 = new JMenuItem("关闭");m01.addActionListener(this);m02.addActionListener(this);m03.addActionListener(this);m04.addActionListener(this);m11 = new JMenuItem("不显过程");m12 = new JMenuItem("显示过程");m11.addActionListener(this);m12.addActionListener(this);m21 = new JMenuItem("帮助主题");m22 = new JMenuItem("关于计算器");m21.addActionListener(this);m22.addActionListener(this);m0.add(m01);m0.add(m02);m0.add(m03);m0.add(m04);m1.add(m11);m1.add(m12);m2.add(m21);m2.addSeparator();m2.add(m22);mb.add(m0);mb.add(m1);mb.add(m2);setJMenuBar(mb);con.add(jtf, BorderLayout.NORTH);con.add(jsp1, BorderLayout.CENTER);con.add(jsp2, BorderLayout.EAST);con.add(jsp3, BorderLayout.WEST);setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);setBounds(100, 100, 800, 260);setResizable(false);setVisible(true);validate();}public void actionPerformed(ActionEvent e) {if (!jtf.getText().equals("error")) {if (e.getSource() == m01) {zc = jtf.getText();} else if (e.getSource() == m02) {if (zc != null) {if (xg == 1) {if (jtf.getText().equals("0"))jtf.setText(zc);elsejtf.setText(jtf.getText() + zc);} elsejtf.setText(zc);}}}if (e.getSource() == m03) { //读取文件Calculator.load.setVisible(true);Calculator.jta.setText(null);String s;if(Calculator.load.getFile()!=null){try{File file=new File(Calculator.load.getDirectory(),Calculator.load.getFile());reader=new FileReader(file);in=new BufferedReader(reader);while((s=in.readLine())!=null){Calculator.jta.append(s+'\n');}in.close();reader.close();}catch(IOException e2){Calculator.jta.append("读取错误");}}} else if (e.getSource() == m04) {System.exit(0);} else if (e.getSource() == m11) {// 换窗体大小,同时换规则setSize(320, 260);remove(jsp2);remove(jsp3);JP2.sf = 0;jtf.setText(String.valueOf(0));xg = 0;// 改变菜单选项的可选性m03.setEnabled(false);m04.setEnabled(false);// 换对齐方式JP2.sf = 0;jtf.setEditable(false);jtf.setBackground(Color.white);jtf.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);validate();} else if (e.getSource() == m12) {setSize(800, 260);add(jsp2, BorderLayout.EAST);add(jsp3, BorderLayout.WEST);JP2.sf = 0;jtf.setText(String.valueOf(0));xg = 1;m03.setEnabled(true);m04.setEnabled(true);JP2.eg = 0;jtf.setEditable(false);jtf.setBackground(Color.white);jtf.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);validate();} else if (e.getSource() == m21) {JOptionPane.showMessageDialog(this,"本计算器以模仿Windows系统自带计算器为主,详情请参照系统计算器“帮助主题”。
简易计算器源代码--java
package calculator;import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.math.BigDecimal;import javax.swing.*;public class Operation extends JFrame implements ActionListener{/****/private static final long serialVersionUID = 1L;private final String str[] = {"7","8","9","/","4","5","6","*","1","2", "3","-",".","0","=","+"};private final JButton[] JB = new JButton[str.length];private final JButton reset = new JButton("CE");private final JTextField display = new JTextField("");Operation(){super("计算器");JPanel panel1 = new JPanel(new BorderLayout());JPanel panel2 = new JPanel(new GridLayout(4,4));panel1.add(BorderLayout.CENTER, display);panel1.add(BorderLayout.EAST, reset);int i;for( i = 0;i < str.length;i++){JB[i] = new JButton(str[i]);panel2.add(JB[i]);}getContentPane().setLayout(new BorderLayout());getContentPane().add(BorderLayout.NORTH,panel1);getContentPane().add(BorderLayout.SOUTH, panel2);setSize(800,800);for(i = 0;i < str.length;i++){JB[i].addActionListener(this);}reset.addActionListener(this);display.addActionListener(this);setVisible(true);setDefaultCloseOperation((WindowConstants.DISPOSE_ON_CLOSE));pack();}public void actionPerformed(ActionEvent e) {// TODO 自动生成的方法存根Object target = e.getSource();String label = e.getActionCommand();if(target == reset){handlereset();}else if("0123456789.".indexOf(label)>=0){handleNumber(label);}elsehandleOperator(label);}private void handleNumber(String key) {// TODO 自动生成的方法存根if ((isFirstDigit)&&("0123456789".indexOf(key)>=0))display.setText(key);else if ((key.equals(".")))display.setText(display.getText() + ".");else if (!key.equals("."))display.setText(display.getText() + key);isFirstDigit = false;}boolean isFirstDigit = true;double number1 = 0.0;double number2 = 0.0;String operator = "=";BigDecimal df ;private void handlereset() {// TODO 自动生成的方法存根display.setText("");isFirstDigit = true;operator = "=";}public void handleOperator(String key) {if (operator.equals("+")){number1 = Double.valueOf(display.getText());number2 = add(number1,number2);df = new BigDecimal(number2);display.setText(String.valueOf( df.setScale(5, BigDecimal.ROUND_HALF_UP).doubleValue()));}else if (operator.equals("-")){number1 = Double.valueOf(display.getText());number2 = sub(number2,number1);df = new BigDecimal(number2);display.setText(String.valueOf( df.setScale(5, BigDecimal.ROUND_HALF_UP).doubleValue()));}else if (operator.equals("*")){number1 = Double.valueOf(display.getText());number2 = mul(number1,number2);df = new BigDecimal(number2);display.setText(String.valueOf( df.setScale(5, BigDecimal.ROUND_HALF_UP).doubleValue()));}else if (operator.equals("/")){number1 = Double.valueOf(display.getText());if(number1 == 0)display.setText("error");else{number2 = div(number2,number1);df = new BigDecimal(number2);display.setText(String.valueOf( df.setScale(5, BigDecimal.ROUND_HALF_UP).doubleValue()));}}else if (operator.equals("=")){number2 = Double.valueOf(display.getText());display.setText(String.valueOf(number2));}operator = key;isFirstDigit = true;}private double div(double key1, double key2) {// TODO 自动生成的方法存根double result = 0.0;result = key1 / key2;return result;}private double mul(double key1, double key2) {// TODO 自动生成的方法存根double result = 0.0;result = key1 * key2;return result;}private double sub(double key1, double key2) { // TODO 自动生成的方法存根double result = 0.0;result = key1 - key2;return result;}private double add(double key1, double key2) { // TODO 自动生成的方法存根double result = 0.0;result = number1 + number2;return result;}public static void main(String[] args) {new Operation();}}。
JAVA计算器源代码
计算器源代码一、计算器源代码文件名:computer1.javaimport java.awt.*;import java.awt.event.*;public class computer1 extends Frame implements ActionListener{//声明窗口类并实现动作事件接口。
Button n0,n1,n2,n3,n4,n5,n6,n7,n8,n9;//声明数字按钮Button op,os,om,od,oe,oc;//声明操作按钮TextField tfd;//声明文本框String flg,rslt;//声明标志串、结果串Panel p1,p2,p3;//声明面板int i1,i2;float flt;computer1(){super("加减乘除计算器");n0 = new Button("0");//实现各按钮n1 = new Button("1");n2 = new Button("2");n3 = new Button("3");n4 = new Button("4");n5 = new Button("5");n6 = new Button("6");n7 = new Button("7");n8 = new Button("8");n9 = new Button("9");op = new Button("加");os = new Button("减");om = new Button("乘");od = new Button("除");oe = new Button("=");oc = new Button("c");tfd = new TextField(20);//实现文本框p1=new Panel();//实现各面板p2=new Panel();p3=new Panel();setLayout(new FlowLayout());//布局设计,用于安排按钮位置p1.add(n0);//将各数字按钮放入p1中p1.add(n1);p1.add(n2);p1.add(n3);p1.add(n4);p1.add(n5);p1.add(n6);p1.add(n7);p1.add(n8);p1.add(n9);p2.add(op);//将各操作按钮放入p2、p3中p2.add(os);p2.add(om);p2.add(od);p3.add(oe);p3.add(oc);setLayout(new BorderLayout());//布局设计,用于安排面板位置add("North",tfd);add("West",p1);add("Center",p2);add("East",p3);n0.addActionListener(this);//注册监听器到各按钮n1.addActionListener(this);n2.addActionListener(this);n3.addActionListener(this);n4.addActionListener(this);n5.addActionListener(this);n6.addActionListener(this);n7.addActionListener(this);n8.addActionListener(this);n9.addActionListener(this);op.addActionListener(this);os.addActionListener(this);om.addActionListener(this);od.addActionListener(this);oe.addActionListener(this);oc.addActionListener(this);addWindowListener(new closeWin());setSize(600,100);//确定窗口的尺寸setVisible(true);}public static void main (String args[]){new computer1();}public void actionPerformed(ActionEvent e){//处理鼠标事件的方法try{//异常处理if(e.getSource()==n0)//按数字键时tfd.setText(tfd.getText()+"0");if(e.getSource()==n1)tfd.setText(tfd.getText()+"1");if(e.getSource()==n2)tfd.setText(tfd.getText()+"2");if(e.getSource()==n3)tfd.setText(tfd.getText()+"3");if(e.getSource()==n4)tfd.setText(tfd.getText()+"4");if(e.getSource()==n5)tfd.setText(tfd.getText()+"5");if(e.getSource()==n6)tfd.setText(tfd.getText()+"6");if(e.getSource()==n7)tfd.setText(tfd.getText()+"7");if(e.getSource()==n8)tfd.setText(tfd.getText()+"8");if(e.getSource()==n9)tfd.setText(tfd.getText()+"9");if(e.getSource()==op){//按加号键时i1 = Integer.parseInt(tfd.getText());tfd.setText("");flg = "op";}if(e.getSource()==os){//按减号键时i1 = Integer.parseInt(tfd.getText());tfd.setText("");flg = "os";}if(e.getSource()==om){//按乘号键时i1 = Integer.parseInt(tfd.getText());tfd.setText("");flg = "om";}if(e.getSource()==od){//按除号键时i1 = Integer.parseInt(tfd.getText());tfd.setText("");flg = "od";}if(e.getSource()==oe){//按等号键时i2 = Integer.parseInt(tfd.getText());if(flg=="op"){rslt=Integer.toString(i1+i2);}if(flg=="os"){rslt=Integer.toString(i1-i2);}if(flg=="om"){rslt=Integer.toString(i1*i2);}if(flg=="od"){//除法需做小数处理flt=((float)i1)/((float)i2);rslt=Float.toString(flt);}tfd.setText(rslt);}if(e.getSource()==oc){//按清除键时tfd.setText("");flg = "";}}catch(Exception ex){}//扑捉到异常,但不进行处理}}class closeWin extends WindowAdapter{ //关闭窗口public void windowClosing(WindowEvent e){Frame frm=(Frame)(e.getSource());frm.dispose();System.exit(0);}}二、计算器界面三、修改后计算器界面。
Java计算器源码
/** To change this template, choose Tools | Templates* and open the template in the editor.*/import java.awt.*;import java.awt.event.*;/**** @author cjwxxq10000*/class CalcAppDemo extends Frame{private TextField t_result;private Panel p_main;//主面板private Panel p_num;//数字面板private Panel p_oper;//操作符面板private Panel p_show;//显示面板private Button b_num[];//数字按钮private Button b_oper[];//操作符按钮public CalcAppDemo(String title){setTitle(title);t_result=new TextField("0.0",21);//定义TextField的初始值为String类"0.0",占用21列p_main=new Panel();p_num=new Panel();p_oper=new Panel();p_show=new Panel();p_main.setLayout(new BorderLayout());p_num.setLayout(new GridLayout(4,3,1,1));p_oper.setLayout(new GridLayout(4,2,1,1));b_num=new Button[12];//定义1-9个Button上的数字为1、2、3、4、5、6、7、8、9//定义第10,11,12个Button上的数字为0、cls、.、for(int i=0;i<9;i++){b_num[i]=new Button(new Integer(i+1).toString());}b_num[9]=new Button("0");b_num[10]=new Button("cls");b_num[11]=new Button(".");//将12个Button添加到p_num(数字面板)上for(int i=0;i<12;i++){p_num.add(b_num[i]);}//定义8个操作符按钮,定义其对应的操作意义b_oper=new Button[8];b_oper[0]=new Button("+");b_oper[1]=new Button("-");b_oper[2]=new Button("*");b_oper[3]=new Button("/");b_oper[4]=new Button("pow");b_oper[5]=new Button("sqrt");b_oper[6]=new Button("+/-");b_oper[7]=new Button("=");//将8个操作符按钮添加到操作符面板上for(int i=0;i<8;i++){p_oper.add(b_oper[i]);}t_result.setEditable(false);//设置返回数值的TextField窗体为不可修改p_show.add(t_result,BorderLayout.NORTH);//将TextField控件t_result添加到p_show 面板上p_main.add(p_show,BorderLayout.NORTH);//将Panel控件p_show添加到p_main面板上,方向为NORTHp_main.add(p_num,BorderLayout.WEST);//将Panel控件p_num添加到p_main面板上,方向为WESTp_main.add(p_oper,BorderLayout.EAST);//将Panel控件p_oper添加到p_mian面板上,方向为EASTthis.add(p_main,BorderLayout.CENTER);//this指代Frame主窗体,将Panel控件p_main添加到主窗体上,方向为正中setSize(400,400);setResizable(false);//设置Frame窗体不能最大化pack();//根据内容自动调整Frame窗体大小//在本窗体中添加WindowAdapter事件,该事件属于WindowListener,在事件中定义windowClosing方法用于退出系统this.addWindowListener(new WindowAdapter(){public void windowClosing(WindowEvent e){System.exit(0);}});//添加ButtonListener事件用于响应Button控件的点击,ButtonListener事件将在下面的ButtonListener类中被定义ButtonListener b1=new ButtonListener();//为12个num的Button批量添加ButtonListener事件for(int i=0;i<12;i++){b_num[i].addActionListener(b1);}//为8个oper的Button批量添加ButtonListener事件for(int i=0;i<8;i++){b_oper[i].addActionListener(b1);}}//在ButtonListener类中定义具体操作,该类继承父类ActionListenerclass ButtonListener implements ActionListener{private String lastOp;//存储上一次操作符private String strVal;//存储数字对应的字符串private double total;//总数private double number;//存储新输入的数private boolean firsttime;//判断是否第一次按下的是操作符按钮private boolean operatorPressed;//判断是否已经按过操作符按钮//创建构造方法ButtonListener,再该构造方法内定义firsttime和strVal的初始值ButtonListener(){//第一次按下操作符firsttime=true;//存储数字对应的字符串为空strVal="";}//事件处理器public void actionPerformed(ActionEvent e){//鼠标点击Button后,系统将返回当初付给button的值String s=((Button) e.getSource()).getLabel().trim();//s.charAt(0);命令使作为String类型的s转换为char类型的数据//Character.isDigit;命令判断Character的值是否为Digit(数字0~9)if(Character.isDigit(s.charAt(0))){//判断是操作数还是操作符handleNumber(s);//调用处理数字按钮的方法}else{calculate(s);//调用处理操作符按钮的方法}}//创建处理操作符按钮的方法void calculate(String op){operatorPressed=true;//operatorPressed用于判断是否已经按过操作符,这里设为true//判断是一元操作符还是二元操作符,并根据操作符类型做计算if(firsttime&&!isUnary(op)){//不是“=”“cls”“sqrt”“+/-”“.”total=getNumberOnDisplay();//将显示屏上的数据赋值到totalfirsttime=false;}if(isUnary(op)){//若是一元操作符handleUnaryOp(op);//执行处理一元操作符方法}else if(lastOp!=null){//若上次的操作符不为空,且不为一元操作符,即当输入为二元操作符时handleBinaryOp(lastOp);//执行处理二元操作符的方法}if(!isUnary(op)){//若直接输入的为非一元操作符,则存储上一次输入的操作符lastOp=op;//存储上一次按下的操作符}}//判断是否是一元操作符boolean isUnary(String s){return s.equals("=")||s.equals("cls")||s.equals("sqrt")||s.equals("+/-")||s.equals(".");}//处理一元操作符void handleUnaryOp(String op){if(op.equals("+/-")){//将显示框中的数字取反//将当前t_result的值存储到number中//negate()方法用于将数字取反//getNumberOnDisplay()方法用于获取t_result中的值number=negate(getNumberOnDisplay()+"");//由于negate(String s)方法的返回值为String类型,故要用到+""t_result.setText("");//将t_result设为空t_result.setText(number+"");//将t_result设为取反后的numberreturn;}else if(op.equals(".")){//将显示框中的数字后添加小数点.handleDecPoint();//执行添加小数点的方法return;}else if(op.equals("sqrt")){//若一元操作符存在且为sqrtnumber=Math.sqrt(getNumberOnDisplay());//调用开根方法Math.sqrt(),处理显示屏上的信息,最终存储到number中t_result.setText("");//清空t_result,即清空显示屏t_result.setText(number+"");//在显示屏上显示新的numberreturn;}else if(op.equals("=")){//若一元操作符存在且为=//在按下“=”前已经按下一个二元运算符if(lastOp!=null&&!isUnary(lastOp)){//上一个操作符不为空且不为一元操作符,即上一个操作符为二元操作符handleBinaryOp(lastOp);//根据二元操作符执行处理二元操作符方法}lastOp=null;//将上次的操作符设为空firsttime=true;//设第一次按下操作符为truereturn;}else{clear();//清空显示屏}}//处理二元运算符void handleBinaryOp(String op){if(op.equals("+")){//若二元操作符为+total+=number;//total=total+number;}else if(op.equals("-")){//若二元操作符为-total-=number;//total=total-number;}else if(op.equals("*")){//若二元操作符*total*=number;//total=total-number;}else if(op.equals("/")){//若二元操作符为"/",当操作符为"/"是有可能被除数为0;所以要trytry{total/=number;//total=total/number;}catch(ArithmeticException ae){}//当被除数为0时,调用ArithmeticException事件}else if(op.equals("pow"))//累乘total=Math.pow(total, number);//total自身累乘number次//t_result.setText("");lastOp=null;//设上次的操作符为空//strVal="";number=0;//设number为0t_result.setText(total+"");//在显示器上显示total值}//该方法用于处理数字按钮void handleNumber(String s){if(!operatorPressed){//尚未按过操作符连接按下的数字按钮的值strVal+=s;//存储数字对应的字符串,即当尚未按下操作符,只按了数字键时,将按下的数字存储到strVal中,strVal=strVal+s}else{//当按下操作符按钮时,清除strVal并存储输入的第一个数值operatorPressed=false;//将是否按过操作符设为falsestrVal=s;//清空strVal,并将第一个数值s存储到strVal中}//将strVal转换为doublenumber=new Double(strVal).doubleV alue();t_result.setText("");//清空显示屏t_result.setText(strVal);//将strVal数值显示到显示屏中}//该方法用于按下“.”按钮void handleDecPoint(){operatorPressed=false;//还未按过操作符//如果该字符串中无“.”,放置一个“.”在字符串末尾if(strVal.indexOf(".")<0){//判断该字符串中是否存在"."strVal+=".";//若不存在,则执行strVal=strVal+".",即在strVal后面添加字符"."}t_result.setText("");//清空显示屏t_result.setText(strVal);//在显示屏中显示新的strVal的值}//该方法用于将一个数求反double negate(String s){operatorPressed=false;//尚未按过操作符按钮//如果是一个整数,去掉小数点后面的0if(number==(int)number){//判断显示屏上的数存储到number上是否为int型s=s.substring(0,s.indexOf("."));//若是,则调用substring方法去掉小数点后的0}//如果无“-”增加再该数前面if(s.indexOf("-")<0){//在s中不存在"-",则执行下一步strVal="-"+s;//在String s前添加String -}else {//如果有“-”则去掉strVal=s.substring(1);//用于去掉串中第一个字符}return new Double(strVal).doubleValue();//返回double strVal}//将显示框中的值转换为Doubledouble getNumberOnDisplay(){return new Double(t_result.getText()).doubleValue();}//清除屏幕并设置所有的标识void clear(){firsttime=true;lastOp=null;strVal="";total=0;number=0;t_result.setText("0");}}public static void main(String args[]){CalcAppDemo c=new CalcAppDemo("简单的计算器程序");c.setVisible(true);}}。
java简单计算器源代码
简单计算器代码package calcultorthree;import java.awt.BorderLayout;//导入边界布局管理器类import java.awt.GridLayout;//导入网格布局管理器类import java.awt.TextField;// 导入文本区域类import java.awt.event.ActionEvent;〃导入事件类import java.awt.event.ActionListener;〃导入事件监听者类import javax.swing.JButton;// 导入按钮类import javax.swing.JFrame;// 导入窗体import javax.swing.JPanel;〃导入面板*本例实现了简单计算器代码,具备加减乘除和正弦功能,旨在抱砖引玉。
熟悉java的同学,可以在此基础上实现更复杂的功能。
* @author Fjsh*/ public class CalcultorThree {〃新建对象,在构造函数中进行初始化JFrame frame;//新建窗体对象JButton buttonzero,buttondot,buttonequal;// 新建按钮“ 0”". ”"=”JButt on butt on plus,butt onminu s,butt onm ultiple,butt on devisi on,butto nsi n,butt on tozero;// 新建按钮“ +”-""“ * ”" / 和归零按钮JButton butt onon e,butt on two,button three,butt on four,button five,butt on six,butt on seve n,butt on eight,butt onnine;// 新建数字“0”“1 ”“ 2”“ 3”“ 4”“ 5”“ 6”“ 7”“ 8”“ 9”JPa nel pan elwest,pa nelce nter,pa neleast;/新建三个面板TextField tf;//新建文本区域对象public CalcultorThree(){//初始化对象tf=new TextField(30);//构造空文本字段,字符宽度为30frame =new JFrame("CalculatorThree");// 构造窗体对象,名称为“ CalculatorThreepan elce nter= new JPan el();〃构造面板,放到窗体中央pan elwest=new JPa nel();〃构造面板,放到窗体西边pan eleast =new JPa nel();〃构造面板,放到窗体东边Handle h=new Handle();〃新建Handle类对象,Handle类为事件监听类//创建数字按钮对象,1、2、3、4、5、6、7、& 9butt onon e=new JButto n( "1");butto ntwo=new JButto n( "2");butto nthree=new JButto n( "3");butto nfour= new JButto n( "4");butt on five=new JButto n( "5");butto nsix=new JButto n( "6");butt on seve n=new JButt on ("7");butto neight=new JButt on ("8");butt onnin e=new JButt on ("9");panelcenter.setLayout(new GridLayout(3,3));〃设置面板布局为网格布局, 3 行3 列〃将数字按钮添加到中间面板pan elce nter.add(butt onon e);pan elce nter.add(butt on two);pan elce nter.add(butt on three);pan elce nter.add(butt on four);pan elce nter.add(butt on five);pan elce nter.add(butt on six);pan elce nter.add(butt on seve n);pan elce nter.add(butt on eight);pan elce nter.add(butt onnin e);//为10个按钮注册事件监听器butt onon e.addAct ion Liste ner(h);butt on two.addAct ion Liste ner(h);butt on three.addAct ion Liste ner(h);butt on four.addActi on Liste ner(h);butt on five.addAct ion Liste ner(h);butt on six.addAct ion Liste ner(h);butt on seve n. addActi on Liste ner(h);butt on eight.addAct ion Liste ner(h);butt onnin e.addAct ion Liste ner(h);//构造按钮“ 0”“ .',注册事件监听器,设置1行3列的布局,添加到到西边的面板butto nzero=new JButt on ("0");butto ndot =new JButt on (".");butt on equal=new JButt on ("=");butt on zero.addAct ion Liste ner(h);butt on dot.addActi on Liste ner(h);butt on equal.addActi on Liste ner(h);pan elwest.setLayout (new GridLayout(3,1));pan elwest.add(butt on zero);pan elwest.add(butt on dot);pan elwest.add(butt on equal);//构造操作按钮“ +”-”““ *”“/”“sin其'中“>00为归零按钮butto nplus=n ew JButto n("+");butt onminus=new JButt on ("-");butto nmultiple=new JButt on ("*");butt on devisi on=new JButt on ("/");butt onsin=new JButt on ("s in ”);butto ntozero=n ew JButto n( ">0");paneleast.setLayout(new GridLayout(3,1));// 设置西边的布局为3 行1 列〃将操作按钮“ +”- ” ““ * ”“ / ”“添n加到西边的面板中pan eleast.add(butt on plus);pan eleast.add(butt onminu s);pan eleast.add(butt onm ultiple);pan eleast.add(butt on devisi on);pan eleast.add(butt onsin);pan eleast.add(butt on tozero);//为操作按钮“ +”-” ““ * ”“ / ”“注册监听貓”butt on plus.addAct ion Liste ner(h);butt onminu s.addAct ion Liste ner(h);butt onm ultiple.addAct ion Liste ner(h);butt on devisi on .addAct ion Liste ner(h);butt onsin. addActi on Liste ner(h);butt on tozero.addActi on Liste ner(h);frame.setLayout(new BorderLayout());// 设置窗体为边界布局frame.add(pa neleast,"East");〃将东边面板pan eleast添加到窗体的东边frame.add(tf,BorderLayout.NORTH); //将tf文本区域添加到窗体的北边,即顶部frame.add(panelwest,BorderLayout.WEST);〃将panelwest面板添加到窗体西边frame.add(panelcenter,BorderLayout.CENTER);〃将panelcenter面板添加到窗体中间frame.pack();//设置窗体大小,适合其子组件的首选大小和布局frame.setLocation(500,500);// 设置窗体显示位置为(500,500)方式frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);〃设置布局窗体默认关闭frame.setVisible(true);// 设置窗体可见}public static void main( Stri ng[] args) {new CalcultorThree();//主方法中新建对象}class Han die impleme nts Actio nListe ner{〃实现动作监听器类int biaozhi=0;〃此标志标志加减乘除操作double flag1=0,flag2=0,flag3=0;//flag1、flag2 为两个操作数,flag3 为结果@Overridepublic void action Performed(Act ionEvent e) { // 方法重写try{//此处可能会产生异常,用try、catch捕捉异常,不用处理if(e.getSource()==buttondot){〃小数点tf.setText("O.");}if(e.getSource()==buttontozero){// 归零操作tf.setText(””);}if(e.getSource()==buttonzero){〃按键0 操作tf.setText(tf.getText()+"0");flag仁Double.parseDouble(tf.getText());〃将文本区域转换成Double 类型, 赋给flag1}if(e.getSource()==buttonone){// 按键1 操作tf.setText(tf.getText()+"1");flag 仁Double.parseDouble(tf.getText());}else if(e.getSource()==buttontwo){〃按键2 操作tf.setText(tf.getText()+"2");flag 仁Double.parseDouble(tf.getText());}else if(e.getSource()==buttonthree){〃按键3 操作tf.setText(tf.getText()+"3");flag 仁Double.parseDouble(tf.getText());}else if(e.getSource()==buttonfour){〃按键4 操作tf.setText(tf.getText()+"4");flag 仁Double.parseDouble(tf.getText());}else if(e.getSource()==buttonfive){// 按键5 操作tf.setText(tf.getText()+"5");flag 仁Double.parseDouble(tf.getText());}else if(e.getSource()==buttonsix){// 按键6 操作tf.setText(tf.getText()+"6");flag 仁Double.parseDouble(tf.getText());}else if(e.getSource()==buttonseven){〃按键7 操作tf.setText(tf.getText()+"7");flag仁Double.parseDouble(tf.getText());}else if(e.getSource()==buttoneight){〃按键8 操作tf.setText(tf.getText()+"8");flag 仁Double.parseDouble(tf.getText());}else if(e.getSource()==buttonnine){// 按键9 操作tf.setText(tf.getText()+"9");flag 仁Double.parseDouble(tf.getText());}if(e.getSource()==buttonplus){〃加法操作tf.setText(””);flag2=flag1;biaozhi=0;}if(e.getSource()==buttonminus){// 减法操作tf.setText(””);flag2=flag1;biaozhi=1;}if(e.getSource()==buttonmultiple){〃乘法操作tf.setText(””);flag2=flag1;biaozhi=2;}if(e.getSource()==buttondevision){〃除法操作tf.setText(””);flag2=flag1;biaozhi=3;}if(e.getSource()==buttonsin){// 正弦操作flag3=Math.s in( flag1);tf.setText(flag3+"");}if(e.getSource()==buttonequal){〃等号操作,利用biaozhi判断进行相应加减乘除操作if(biaozhi==0){flag3=flag1+flag2;}if(biaozhi==1){flag3=flag1-flag2;}if(biaozhi==2){flag3=flag1*flag2;}if(biaozhi==3){ flag3=flag1/flag2;}tf.setText(flag3+"");}}catch(Excepti on ex){}}}}。
java版计算器源代码
java版计算器源代码:import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.*;import java.awt.*;import java.math.BigDecimal;import java.math.MathContext;import java.math.RoundingMode;import java.awt.Color;/*** java版计算器*/public class Calculator extends JFrame {final int WIN_W = 250, WIN_H = 250;JPanel myPanel, panelSuper;public Calculator() {// 主面板panelSuper = new JPanel();panelSuper.setLayout(null);// 设置窗口位置double width = Toolkit.getDefaultToolkit().getScreenSize().width; double height =Toolkit.getDefaultToolkit().getScreenSize().height;this.setBounds((int) (width - WIN_W) / 2, (int) (height - WIN_H) / 2,WIN_W, WIN_H);// 窗口配置this.setTitle("java版计算器");this.validate();this.setResizable(false);this.setVisible(true);this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);// 添加计算器按钮面板myPanel = new MyPanel();this.add(myPanel, BorderLayout.CENTER);}public static void main(String[] args) {new Calculator();}/*** 计算器按钮面板类*/class MyPanel extends JPanel implements ActionListener {JButton button1, button2, button3, button4, button5, button6, button7,button8, button9, button0, buttonJia, buttonJian, buttonCheng,buttonChu, buttonDeng, buttonDian, buttonC, buttonDel, buttonZF, buttonGH;JTextField jTextField; // 计算器显示屏char oper; // 操作符String key, allKey = "1234567890.±del", jjccKey = " -*/";BigDecimal d1, d2;boolean first;public MyPanel() {// 设置布局this.setLayout(new FlowLayout(FlowLayout.LEFT, 4, 5));// 计算器显示屏jTextField = new JTextField(21);jTextField.setHorizontalAlignment(JTextField.RIGHT);jTextField.setEditable(false);jTextField.setBackground(new Color(255, 255, 255));jTextField.setText("0");this.add(jTextField);// 计算器按钮button1 = new JButton("1");button2 = new JButton("2");button3 = new JButton("3");button4 = new JButton("4");button5 = new JButton("5");button6 = new JButton("6");button7 = new JButton("7");button8 = new JButton("8");button9 = new JButton("9");button0 = new JButton("0");buttonJia = new JButton(" ");buttonJian = new JButton("-");buttonCheng = new JButton("*");buttonChu = new JButton("/");buttonDeng = new JButton("=");buttonDian = new JButton(".");buttonDel = new JButton("del");buttonC = new JButton("c");buttonZF = new JButton("±");buttonGH = new JButton("√");button1.setPreferredSize(new Dimension(55, 30));button2.setPreferredSize(new Dimension(55, 30));button3.setPreferredSize(new Dimension(55, 30));button4.setPreferredSize(new Dimension(55, 30));button5.setPreferredSize(new Dimension(55, 30));button6.setPreferredSize(new Dimension(55, 30));button7.setPreferredSize(new Dimension(55, 30));button8.setPreferredSize(new Dimension(55, 30));button9.setPreferredSize(new Dimension(55, 30));button0.setPreferredSize(new Dimension(55, 30));buttonJia.setPreferredSize(new Dimension(55, 30)); buttonJian.setPreferredSize(new Dimension(55, 30)); buttonCheng.setPreferredSize(new Dimension(55, 30)); buttonChu.setPreferredSize(new Dimension(55, 30)); buttonDeng.setPreferredSize(new Dimension(55, 30)); buttonDian.setPreferredSize(new Dimension(55, 30)); buttonDel.setPreferredSize(new Dimension(55, 30)); buttonC.setPreferredSize(new Dimension(55, 30));buttonZF.setPreferredSize(new Dimension(55, 30));buttonGH.setPreferredSize(new Dimension(55, 30)); this.add(buttonDel);this.add(buttonC);this.add(buttonZF);this.add(buttonGH);this.add(button1);this.add(button2);this.add(button3);this.add(buttonJia);this.add(button4);this.add(button5);this.add(button6);this.add(buttonJian);this.add(button7);this.add(button8);this.add(button9);this.add(buttonCheng);this.add(button0);this.add(buttonDian);this.add(buttonDeng);this.add(buttonChu);buttonDel.addActionListener(this);buttonC.addActionListener(this);buttonZF.addActionListener(this);buttonGH.addActionListener(this);button1.addActionListener(this);button2.addActionListener(this);button3.addActionListener(this);button4.addActionListener(this);button5.addActionListener(this);button6.addActionListener(this);button7.addActionListener(this);button8.addActionListener(this);button9.addActionListener(this);button0.addActionListener(this);buttonJia.addActionListener(this);buttonJian.addActionListener(this);buttonCheng.addActionListener(this);buttonChu.addActionListener(this);buttonDeng.addActionListener(this);buttonDian.addActionListener(this);// 计算器初始化init();}/*** 计算器初始化*/public void init() {d1 = new BigDecimal("0");d1 = new BigDecimal("0");key = "=";oper = '=';jTextField.setText("0");first = true; // 用于标记是否进行连续操作(例如按键顺序为“9*9====”,第一次等于first由true变为false,如果!first,按等号相当于用上一次的结果与第二个操作数相乘)}/*** 按钮监听*/public void actionPerformed(ActionEvent e) {JButton b = (JButton) e.getSource();if (b == buttonDian) { // 按下.jTextField.setText(jTextField.getText() ".");if (first) {d2 = d1 = getNum();} else {d2 = getNum();}} else if (b == buttonZF) {// 按下±BigDecimal d = getNum();d = new BigDecimal("0").subtract(d);setFormatNum(d);if (first) {d2 = d1 = getNum();} else {d2 = getNum();}} else if (b == buttonDel) {// 按下delif (jTextField.getText().length() == 1|| jTextField.getText().length() == 2&& jTextField.getText().startsWith("-")) { jTextField.setText("0");} else {String s = jTextField.getText();s = s.substring(0, s.length() - 1);if (s.endsWith("E ") || s.endsWith("E-"))s = s.substring(0, s.length() - 2);jTextField.setText(s);if (first) {d2 = d1 = getNum();} else {d2 = getNum();}}} else if (b == buttonC) {// 按下cinit();} else if (b == buttonJia) {// 按下BigDecimal s;if (!first && allKey.indexOf(key) >= 0) {if (oper == '-' || oper == '/') {s = operate(d1, oper, d2);} else {s = operate(d2, oper, d1);}setFormatNum(s);}// 如果不是第一次,且上一次操作是对数字进行操作else {first = false;}d2 = d1 = getNum();// System.out.print("111我执行啦\n");oper = ' ';} else if (b == buttonJian) {// 按下-BigDecimal s;if (!first && allKey.indexOf(key) >= 0) {s = operate(d1, oper, d2);setFormatNum(s);}// 如果不是第一次,且上一次操作是对数字进行操作 else {first = false;}d2 = d1 = getNum();oper = '-';} else if (b == buttonCheng) {// 按下*BigDecimal s;if (!first && allKey.indexOf(key) >= 0) {if (oper == '-' || oper == '/') {s = operate(d1, oper, d2);} else {s = operate(d2, oper, d1);}setFormatNum(s);}// 如果不是第一次,且上一次操作是对数字进行操作 else {first = false;}d2 = d1 = getNum();oper = '*';} else if (b == buttonChu) {// 按下/BigDecimal s;if (!first && allKey.indexOf(key) >= 0) {s = operate(d1, oper, d2);setFormatNum(s);}// 如果不是第一次,且上一次操作是对数字进行操作 else {first = false;}d2 = d1 = getNum();oper = '/';} else if (b == buttonGH) {// 按下平方根if (jTextField.getText().startsWith("-")) {init();return;}BigDecimal d = getNum();MathContext mc = new MathContext(10, RoundingMode.HALF_DOWN);d = new BigDecimal(Math.sqrt(d.doubleValue()), mc);setFormatNum(d);if (first) {d2 = d1 = getNum();} else {d2 = getNum();}} else if (b == buttonDeng) {// 按下=BigDecimal s = null;d2 = getNum();if (!key.equals("=")) {s = operate(d1, oper, d2);} else {s = operate(d2, oper, d1);}if (oper != '=' && !key.equals("=")) {// 上一次操作为 -*/d1 = getNum();}setFormatNum(s);first = true;} else { // 按下其他按钮if (this.jTextField.getText().equals("0")|| allKey.indexOf(key) == -1) {this.jTextField.setText(b.getText());} else {this.jTextField.setText(jTextField.getText()b.getText());}if (first) {d2 = d1 = getNum();} else {d2 = getNum();}// d2作被加数:d2 d1}key = b.getText();}/*** 获取操作数** @return 操作数*/public BigDecimal getNum() {BigDecimal d = new BigDecimal(jTextField.getText());return d;}public void setFormatNum(BigDecimal dd) {MathContext mc = new MathContext(18, RoundingMode.HALF_DOWN);BigDecimal d = new BigDecimal(dd.toString(), mc);String num = d.toString();if (num.endsWith(".0"))num = num.replaceAll("\\.0", "");this.jTextField.setText(num);}/*** 计算** @param a1* 操作数1* @param c* 操作符* @param a2* 操作数2* @return*/public BigDecimal operate(BigDecimal a1, char c, BigDecimal a2) {MathContext mc = new MathContext(10, RoundingMode.HALF_DOWN); switch (c) {case ' ':return a1.add(a2);case '-':return a1.subtract(a2);case '*':return a1.multiply(a2);case '/':if (pareTo(new BigDecimal("0")) == 0) {init();return new BigDecimal("0"); }return a1.divide(a2, mc);default:return a2;}}}}。
java版计算器源代码
jb[3] = new JButton("/");
jb[4] = new JButton(".");
jb[5] = new JButton("sin");
jb[6] = new JButton("cos");
jb[7] = new JButton("tan");
ContaineidLayout gl = new GridLayout(7, 4, 2, 2);
jp1.add(jl);
jp1.add(jt);
jp2.setLayout(gl);
jp2.add(jb[5]);
jp2.add(jb[6]);
setVisible(true);
}
class Lis implements ActionListener {
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
double d = 0.0;
private JButton ok, cancel, C;
private JTextField jt;
private JPanel jp1, jp2;
private JButton[] jb;
private static String str = "";
public Calculator() {
jb[8] = new JButton("aqrt");
计算器的Java源代码
计算器程序的源代码import java.awt.*;import java.awt.event.*;import javax.swing.*;public class Calculator extends Frame implements ActionListener, WindowListener{private Container container;private GridBagLayout layout;private GridBagConstraints constraints;private JTextField displayField; //计算结果显示区private String lastCommand; //保存+,-,*,/,=命令0private double result; //保存计算结果private boolean start; //判断是否为数字的开始private JMenuBar menubar;private JMenuItem m_exit,m2_ejz,m2_bjz;private Dialog dialog;private Label label_dialog;private JButton button_sqrt,button_plusminus,button_CE,button_cancel,button_1,button_2,button_3,button_4,button_5,button_6,button_7,button_8,button_9,button_0, button_plus,button_minus,button_multiply,button_divide,button_point,button_equal,button_log,button_tan,button_cos,button_sin,button_exp;public Calculator() //构造方法设置布局、为按钮注册事件监听器{super("Calculator");this.setLocation(240,200);this.setSize(350,300);this.setResizable(true);this.setLayout(new GridLayout(7,1));this.addmyMenu(); //调用成员方法添加菜单displayField=new JTextField(30);this.add(displayField);displayField.setEditable(true);start=true;result=0;lastCommand = "=";JPanel panel0=new JPanel();panel0.setLayout(new GridLayout(1,4,4,4));JPanel panel1=new JPanel();panel1.setLayout(new GridLayout(1,5,4,4));this.add(panel1);button_sqrt=new JButton("sqrt");button_plusminus=new JButton("+/-");button_exp=new JButton("exp");button_CE=new JButton("C");button_cancel=new JButton("CE");JPanel panel2=new JPanel();panel2.setLayout(new GridLayout(1,5,4,4));this.add(panel2);button_7=new JButton("7");button_8=new JButton("8");button_9=new JButton("9");button_log=new JButton("log");button_divide=new JButton("/");JPanel panel3=new JPanel();panel3.setLayout(new GridLayout(1,5,4,4));this.add(panel3);button_4=new JButton("4");button_5=new JButton("5");button_6=new JButton("6");button_tan=new JButton("tan");button_multiply=new JButton("*");JPanel panel4=new JPanel();panel4.setLayout(new GridLayout(1,5,4,4));this.add(panel4);button_1=new JButton("1");button_2=new JButton("2");button_3=new JButton("3");button_cos=new JButton("cos");button_minus=new JButton("-");JPanel panel5=new JPanel();panel5.setLayout(new GridLayout(1,5,4,4));this.add(panel5);button_0=new JButton("0");button_point=new JButton(".");button_equal=new JButton("=");button_sin=new JButton("sin");button_plus=new JButton("+");panel1.add(button_sqrt);panel1.add(button_plusminus);panel1.add(button_exp);panel1.add(button_CE);panel1.add(button_cancel);panel2.add(button_7);panel2.add(button_8);panel2.add(button_9);panel2.add(button_log);panel2.add(button_divide);panel3.add(button_4);panel3.add(button_5);panel3.add(button_6);panel3.add(button_tan);panel3.add(button_multiply);panel4.add(button_1);panel4.add(button_2);panel4.add(button_3);panel4.add(button_cos);panel4.add(button_minus);panel5.add(button_0);panel5.add(button_point);panel5.add(button_equal);panel5.add(button_sin);panel5.add(button_plus);button_sqrt.addActionListener(this);button_plusminus.addActionListener(this);button_exp.addActionListener(this);button_CE.addActionListener(this);button_cancel.addActionListener(this);button_7.addActionListener(this);button_8.addActionListener(this);button_9.addActionListener(this);button_log.addActionListener(this);button_divide.addActionListener(this);button_4.addActionListener(this);button_5.addActionListener(this);button_6.addActionListener(this);button_tan.addActionListener(this);button_multiply.addActionListener(this);button_1.addActionListener(this);button_2.addActionListener(this);button_3.addActionListener(this);button_cos.addActionListener(this);button_minus.addActionListener(this);button_0.addActionListener(this);button_point.addActionListener(this);button_equal.addActionListener(this);button_sin.addActionListener(this);button_plus.addActionListener(this);this.addWindowListener(new WinClose()); //注册窗口监听器this.setVisible(true);}private void addmyMenu() //菜单的添加{JMenuBar menubar=new JMenuBar();this.add(menubar);JMenu m1=new JMenu("选项");JMenu m2=new JMenu("进制转换");JMenuItem m1_exit=new JMenuItem("退出");m1_exit.addActionListener(this);JMenuItem m2_ejz=new JMenuItem("二进制");m2_ejz.addActionListener(this);JMenuItem m2_bjz=new JMenuItem("八进制");m2_bjz.addActionListener(this);JMenu m3 = new JMenu(" 帮助");JMenuItem m3_Help = new JMenuItem("作者");m3_Help.addActionListener(this);dialog = new Dialog(this,"关于",true); //模式窗口 dialog.setSize(240,80);label_dialog = new Label("",Label.CENTER); //标签的字符串为空,居中对齐dialog.add(label_dialog);dialog.addWindowListener(this); //为对话框注册窗口事件监听器m1.add(m1_exit);menubar.add(m1);m2.add(m2_ejz);m2.add(m2_bjz);menubar.add(m2);m3.add(m3_Help);menubar.add(m3); }public void actionPerformed(ActionEvent e) //按钮的单击事件处理方法{if(e.getSource().equals(button_1)||e.getSource().equals(button_2)||e.getSource().equals(button_3)||e.getSource().equals(button_4)||e.getSource().equals(button_5)|| e.getSource().equals(button_6)||e.getSource().equals(button_7)|| e.getSource().equals(button_8)||e.getSource().equals(button_9) ||e.getSource().equals(button_0)||e.getSource().equals(button_point)||e.getSource().equals(button_plusmin us)||e.getSource().equals(button_cancel)||e.getSource().equals(button_CE)){ //非运算符的处理方法String input=e.getActionCommand();if (start){displayField.setText("");start=false;if(input.equals("+/-"))displayField.setText(displayField.getText()+"-");}if(!input.equals("+/-")){String str=displayField.getText();if(input.equals("C")) //退格键的实现方法{if(str.length()>0)displayField.setText(str.substring(0,str.length()-1));}else if(input.equals("CE")) //清零键的实现方法{displayField.setText("0");start=true;}elsedisplayField.setText(displayField.getText()+input);}}else if (e.getActionCommand()=="二进制") //二进制的转换{int n=Integer.parseInt(displayField.getText());displayField.setText(Integer.toBinaryString(n));}else if (e.getActionCommand()=="八进制") //八进制的转换{int n=Integer.parseInt(displayField.getText());displayField.setText(Integer.toOctalString(n));}else if (e.getActionCommand()=="退出") //选项中退出的处理方法{System.exit(0);}else if (e.getActionCommand()=="作者") //按下'帮助'菜单栏中用法的处理方法{label_dialog.setText("熊瑛琪制作 \n学号:080320618");dialog.setLocation(400,250);dialog.setVisible(true);}else //各运算符的识别{String command=e.getActionCommand();if(start){lastCommand=command;}else{calculate(Double.parseDouble(displayField.getText()));lastCommand=command;start=true;}}}public void calculate(double x) //各运算符的具体运算方法 {double d=0;if (lastCommand.equals("+"))result+= x;else if (lastCommand.equals("-"))result-=x;else if (lastCommand.equals("*"))result*=x;else if (lastCommand.equals("/"))result/=x;else if (lastCommand.equals("="))result=x;else if (lastCommand.equals("sqrt")){d=Math.sqrt(x);result=d;}else if (lastCommand.equals("exp")){d=Math.exp(x);result=d;}else if (lastCommand.equals("log")){d=Math.log(x);result=d;}else if (lastCommand.equals("tan")){d=Math.tan(x);result=d;}else if (lastCommand.equals("cos")){d=Math.cos(x);result=d;}else if (lastCommand.equals("sin")){d=Math.sin(x);result=d;}displayField.setText(""+ result);}public void windowClosing(WindowEvent e){if(e.getSource()==dialog)dialog.setVisible(false); //隐藏对话框elseSystem.exit(0);}public void windowOpened(WindowEvent e) { }public void windowActivated(WindowEvent e) { }public void windowDeactivated(WindowEvent e) { }public void windowClosed(WindowEvent e) { }public void windowIconified(WindowEvent e) { }public void windowDeiconified(WindowEvent e) { }public static void main(String args[]){Calculator calculator=new Calculator();}}class WinClose implements WindowListener{public void windowClosing(WindowEvent e) //单击窗口关闭按钮时触发并执行实现窗口监听器接口{System.exit(0); //结束程序运行}public void windowOpened(WindowEvent e){}public void windowActivated(WindowEvent e){}public void windowDeactivated(WindowEvent e){}public void windowClosed(WindowEvent e){}public void windowIconified(WindowEvent e){}public void windowDeiconified(WindowEvent e){}}程序运行在对程序进行测试时发现“sin”函数出现异常点击“sin”然后输入“90”出现以下情况经过对程序代码的检查发现在下面方法中public void calculate(double x) //各运算符的具体运算方法{double d=0;if (lastCommand.equals("+"))result+= x;else if (lastCommand.equals("-"))result-=x;else if (lastCommand.equals("*"))result*=x;else if (lastCommand.equals("/"))result/=x;else if (lastCommand.equals("="))result=x;else if (lastCommand.equals("sqrt")){d=Math.sqrt(x);result=d;}else if (lastCommand.equals("exp")){d=Math.exp(x);result=d;}else if (lastCommand.equals("log")){d=Math.log(x);result=d;}else if (lastCommand.equals("tan")){d=Math.tan(x);result=d;}else if (lastCommand.equals("cos")){d=Math.cos(x);result=d;}displayField.setText(""+ result); }发现遗漏以下代码else if (lastCommand.equals("sin")){d=Math.sin(x);result=d;}修改后再次进行测试输入“1.5707963”(约为0.5*pi)再键入“sin”得以下结果可见程序修改成功。
计算器java 源代码
presssin();
else if(e.getSource()==mat_tan)
presstan();
else if(e.getSource()==mat_cos)
presscos();
else if(e.getSource()==do_ans)
p0=new Panel(); //显示屏的布局
p0.setLayout(g0);
p0.add(number);
p0.setBounds(50,20,600,70);//左50上20长600宽70
//按纽的布局
p1=new Panel();
p1.setLayout(g1);
p1.add(num_1);//第一排按纽
p1.add(num_7);//第三排按纽
p1.add(num_8);
p1.add(num_9);
p1.add(mat_sin);
p1.add(mat_cos);
பைடு நூலகம்
p1.add(num_0);//第四排按钮
p1.add(num_p);
p1.add(do_ans);
p1.add(do_dele);
//定义各个控件的样式
number=new JTextField(20);//构造宽度为20个字符的文本框
number.setHorizontalAlignment(JTextField.RIGHT); //设置水平对齐方式
number.setEnabled(true);
number.setText("0");
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
import java.awt.BorderLayout;import java.awt.Color;import java.awt.GridLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JPanel;import javax.swing.JTextField;/*** 一个计算器,与Windows附件自带计算器的标准版功能、界面相仿。
但还不支持键盘操作。
*/public class Calculator extends JFrame implements ActionListener {/** 计算器上的键的显示名字*/private final String[] KEYS = { "7", "8", "9", "/", "sqrt", "4", "5", "6","*", "%", "1", "2", "3", "-", "1/x", "0", "+/-", ".", "+", "=" };/** 计算器上的功能键的显示名字*/private final String[] COMMAND = { "Backspace", "CE", "C" };/** 计算器左边的M的显示名字*/private final String[] M = { " ", "MC", "MR", "MS", "M+" };/** 计算器上键的按钮*/private JButton keys[] = new JButton[KEYS.length];/** 计算器上的功能键的按钮*/private JButton commands[] = new JButton[COMMAND.length];/** 计算器左边的M的按钮*/private JButton m[] = new JButton[M.length];/** 计算结果文本框*/private JTextField resultText = new JTextField("0");// 标志用户按的是否是整个表达式的第一个数字,或者是运算符后的第一个数字private boolean firstDigit = true;// 计算的中间结果。
private double resultNum = 0.0;// 当前运算的运算符private String operator = "=";// 操作是否合法private boolean operateValidFlag = true;/*** 构造函数*/public Calculator() {super();// 初始化计算器init();// 设置计算器的背景颜色this.setBackground(Color.LIGHT_GRAY);this.setTitle("计算器");// 在屏幕(500, 300)坐标处显示计算器this.setLocation(500, 300);// 不许修改计算器的大小this.setResizable(false);// 使计算器中各组件大小合适this.pack();}/*** 初始化计算器*/private void init() {// 文本框中的内容采用右对齐方式resultText.setHorizontalAlignment(JTextField.RIGHT);// 不允许修改结果文本框resultText.setEditable(false);// 设置文本框背景颜色为白色resultText.setBackground(Color.white);// 初始化计算器上键的按钮,将键放在一个画板内JPanel calckeysPanel = new JPanel();// 用网格布局器,4行,5列的网格,网格之间的水平方向间隔为3个象素,垂直方向间隔为3个象素calckeysPanel.setLayout(new GridLayout(4, 5, 3, 3));for (int i = 0; i < KEYS.length; i++) {keys[i] = new JButton(KEYS[i]);calckeysPanel.add(keys[i]);keys[i].setForeground(Color.blue);}// 运算符键用红色标示,其他键用蓝色表示keys[3].setForeground(Color.red);keys[8].setForeground(Color.red);keys[13].setForeground(Color.red);keys[18].setForeground(Color.red);keys[19].setForeground(Color.red);// 初始化功能键,都用红色标示。
将功能键放在一个画板内JPanel commandsPanel = new JPanel();// 用网格布局器,1行,3列的网格,网格之间的水平方向间隔为3个象素,垂直方向间隔为3个象素commandsPanel.setLayout(new GridLayout(1, 3, 3, 3));for (int i = 0; i < COMMAND.length; i++) {commands[i] = new JButton(COMMAND[i]);commandsPanel.add(commands[i]);commands[i].setForeground(Color.red);}// 初始化M键,用红色标示,将M键放在一个画板内JPanel calmsPanel = new JPanel();// 用网格布局管理器,5行,1列的网格,网格之间的水平方向间隔为3个象素,垂直方向间隔为3个象素calmsPanel.setLayout(new GridLayout(5, 1, 3, 3));for (int i = 0; i < M.length; i++) {m[i] = new JButton(M[i]);calmsPanel.add(m[i]);m[i].setForeground(Color.red);}// 下面进行计算器的整体布局,将calckeys和command画板放在计算器的中部,// 将文本框放在北部,将calms画板放在计算器的西部。
// 新建一个大的画板,将上面建立的command和calckeys画板放在该画板内JPanel panel1 = new JPanel();// 画板采用边界布局管理器,画板里组件之间的水平和垂直方向上间隔都为3象素panel1.setLayout(new BorderLayout(3, 3));panel1.add("North", commandsPanel);panel1.add("West", calckeysPanel);// 建立一个画板放文本框JPanel top = new JPanel();top.setLayout(new BorderLayout());top.add("Center", resultText);// 整体布局getContentPane().setLayout(new BorderLayout(3, 5));getContentPane().add("North", top);getContentPane().add("Center", panel1);getContentPane().add("West", calmsPanel);// 为各按钮添加事件侦听器// 都使用同一个事件侦听器,即本对象。
本类的声明中有implements ActionListenerfor (int i = 0; i < KEYS.length; i++) {keys[i].addActionListener(this);}for (int i = 0; i < COMMAND.length; i++) {commands[i].addActionListener(this);}for (int i = 0; i < M.length; i++) {m[i].addActionListener(this);}}/*** 处理事件*/public void actionPerformed(ActionEvent e) {// 获取事件源的标签String label = e.getActionCommand();if (label.equals(COMMAND[0])) {// 用户按了"Backspace"键handleBackspace();} else if (label.equals(COMMAND[1])) {// 用户按了"CE"键resultText.setText("0");} else if (label.equals(COMMAND[2])) {// 用户按了"C"键handleC();} else if ("0123456789.".indexOf(label) >= 0) {// 用户按了数字键或者小数点键handleNumber(label);// handlezero(zero);} else {// 用户按了运算符键handleOperator(label);}}/*** 处理Backspace键被按下的事件*/private void handleBackspace() {String text = resultText.getText();int i = text.length();if (i > 0) {// 退格,将文本最后一个字符去掉text = text.substring(0, i - 1);if (text.length() == 0) {// 如果文本没有了内容,则初始化计算器的各种值resultText.setText("0");firstDigit = true;operator = "=";} else {// 显示新的文本resultText.setText(text);}}}/*** 处理数字键被按下的事件** @param key*/private void handleNumber(String key) {if (firstDigit) {// 输入的第一个数字resultText.setText(key);} else if ((key.equals(".")) && (resultText.getText().indexOf(".") < 0)) {// 输入的是小数点,并且之前没有小数点,则将小数点附在结果文本框的后面resultText.setText(resultText.getText() + ".");} else if (!key.equals(".")) {// 如果输入的不是小数点,则将数字附在结果文本框的后面resultText.setText(resultText.getText() + key);}// 以后输入的肯定不是第一个数字了firstDigit = false;}/*** 处理C键被按下的事件*/private void handleC() {// 初始化计算器的各种值resultText.setText("0");firstDigit = true;operator = "=";}/*** 处理运算符键被按下的事件** @param key*/private void handleOperator(String key) {if (operator.equals("/")) {// 除法运算// 如果当前结果文本框中的值等于0if (getNumberFromText() == 0.0) {// 操作不合法operateValidFlag = false;resultText.setText("除数不能为零");} else {resultNum /= getNumberFromText();}} else if (operator.equals("1/x")) {// 倒数运算if (resultNum == 0.0) {// 操作不合法operateValidFlag = false;resultText.setText("零没有倒数");} else {resultNum = 1 / resultNum;}} else if (operator.equals("+")) {// 加法运算resultNum += getNumberFromText();} else if (operator.equals("-")) {// 减法运算resultNum -= getNumberFromText();} else if (operator.equals("*")) {// 乘法运算resultNum *= getNumberFromText();} else if (operator.equals("sqrt")) {// 平方根运算resultNum = Math.sqrt(resultNum);} else if (operator.equals("%")) {// 百分号运算,除以100resultNum = resultNum / 100;} else if (operator.equals("+/-")) {// 正数负数运算resultNum = resultNum * (-1);} else if (operator.equals("=")) {// 赋值运算resultNum = getNumberFromText();}if (operateValidFlag) {// 双精度浮点数的运算long t1;double t2;t1 = (long) resultNum;t2 = resultNum - t1;if (t2 == 0) {resultText.setText(String.valueOf(t1));} else {resultText.setText(String.valueOf(resultNum));}}// 运算符等于用户按的按钮operator = key;firstDigit = true;operateValidFlag = true;}/*** 从结果文本框中获取数字** @return*/private double getNumberFromText() {double result = 0;try {result = Double.valueOf(resultText.getText()).doubleValue();} catch (NumberFormatException e) {}return result;}public static void main(String args[]) {Calculator calculator1 = new Calculator();calculator1.setVisible(true);calculator1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);}}最新文件仅供参考已改成word文本。