科学计算器程序Java代码
java科学计算器源代码
import java.awt.*;import javax.swing.*;import java.awt.event.*;class Counter extends WindowAdapter{static JFrame f=new JFrame("计算器"); static JTextField text1=new JTextField("0."); static String source="";static String cal="";static String object="";static boolean flag=false;static boolean flag1=true;static boolean flag2=false;public void init(){try{Container c=f.getContentPane();JPanel pan1=new JPanel();JButton b1=new JButton("1");JButton b2=new JButton("2");JButton b3=new JButton("3");JButton b4=new JButton("4");JButton b5=new JButton("5");JButton b6=new JButton("6");JButton b7=new JButton("7");JButton b8=new JButton("8");JButton b9=new JButton("9");JButton b0=new JButton("0");JButton b11=new JButton("+");JButton b12=new JButton("-");JButton b13=new JButton("*");JButton b14=new JButton("/");JButton b15=new JButton(".");JButton b16=new JButton("=");JButton bclar=new JButton("清零");text1.setHorizontalAlignment(JTextField.RIGHT);c.add(text1,"North");c.add(pan1);A aa=new A();Result re=new Result();Opertion op=new Opertion();Clar cl=new Clar();b1.addActionListener(aa);b2.addActionListener(aa);b3.addActionListener(aa);b4.addActionListener(aa);b5.addActionListener(aa);b6.addActionListener(aa);b7.addActionListener(aa);b8.addActionListener(aa);b9.addActionListener(aa);b0.addActionListener(aa);b11.addActionListener(op);b12.addActionListener(op);b13.addActionListener(op);b14.addActionListener(op);b16.addActionListener(re);b15.addActionListener(aa);bclar.addActionListener(cl);pan1.add(b1);pan1.add(b2);pan1.add(b3);pan1.add(b11);pan1.add(b4);pan1.add(b5);pan1.add(b6);pan1.add(b12);pan1.add(b7);pan1.add(b8);pan1.add(b9);pan1.add(b13);pan1.add(b0);pan1.add(b15);pan1.add(b16);pan1.add(b14);pan1.add(bclar);f.setSize(200,220);f.setVisible(true);}catch(Exception e){System.out.println(e.getMessage());}}class A implements ActionListener{public void actionPerformed(ActionEvent e) {String a=text1.getText();String s=e.getActionCommand();if(a.equals("0.")||a.equals("+")||a.equals("-")||a.equals("*")||a.equals("/")) text1.setText(s);else {if(flag2){text1.setText(s);flag2=false;}elsetext1.setText(a+s);}}}class Opertion implements ActionListener{public void actionPerformed(ActionEvent e){cal=e.getActionCommand();if(flag1==true)source=text1.getText();text1.setText(cal);flag1=false;flag=true;}}class Result implements ActionListener{public void actionPerformed(ActionEvent e){double num1;num1=Double.parseDouble(source); object=text1.getText();double num2;num2=Double.parseDouble(object); double result=0;if(cal.equals("+"))result=num1+num2;if(cal.equals("-"))result=num1-num2;if(cal.equals("*"))result=num1*num2;if(cal.equals("/"))if(num2==0)text1.setText("除数不能为0");elseresult=num1/num2;String s1=Double.toString(result);text1.setText(s1);flag1=true;flag2=true;}}class Clar implements ActionListener{public void actionPerformed(ActionEvent e) {text1.setText("0.");}}public static void main(String[] args){Counter count=new Counter();count.init();}public void windowClosing(WindowEvent e){ System.exit(1);}public void windowOpened(WindowEvent e){} public void windowIconified(WindowEvent e){} public void windowDeiconified(WindowEvent e){} public void windowClosed(WindowEvent e){} public void windowActivated(WindowEvent e){} public void windowDeactivated(WindowEvent e){} }。
科学计算器程序Java代码
科学计算器程序Java代码MC:清除独立内存里的数字MR:读出独立内存数字MS:将显示数字保存到独立内存,并取代内存中原有数字M+:将显示数字向独立内存累加(独立内存是一个临时寄放数字的存储器,方便计算)CE:纠错键(CLEAR ERROR).输入数字有错,按它可以重新输入C:表示清零,将计算器恢复到开机状态功能举例:源程序如下:import java.awt.BorderLayout;import javax.swing.JRadioButtonMenuItem; import javax.swing.JTextField;public class Calucator extends JFrame { private JTextField tf;private JPanel panel1, panel2, panel3, panel4;private JMenuBar myBar;private JMenu menu1, menu2, menu3;private JMenuItem editItem1, editItem2, help1, help2, help3;private JRadioButtonMenuItem seeItem1, seeItem2;//单选框private JCheckBoxMenuItem seeItem3;//复选框private ButtonGroup bgb;private String back;private boolean IfResult = true, flag = false;private String oper = "=";private double result = 0;private Num numActionListener;private DecimalFormat df;public Calucator(){super("科学计算器");//设置标题栏df= new DecimalFormat("#.####");//保留四位小数this.setLayout(new BorderLayout(10, 5));panel1 = new JPanel(new GridLayout(1, 3, 10, 10));panel2 = new JPanel(new GridLayout(5, 6, 5, 5));//5行6列panel3 = new JPanel(new GridLayout(5, 1, 5, 5));panel4= new JPanel(new BorderLayout(5, 5));/***菜单栏*/myBar = new JMenuBar();menu1 = new JMenu("编辑(E)");menu2 = new JMenu("查看(V)");menu3 = new JMenu("帮助(H)");menu1.setFont(new Font("宋体", Font.PLAIN, 12));menu2.setFont(new Font("宋体", Font.PLAIN, 12));menu3.setFont(new Font("宋体", Font.PLAIN, 12));/***编辑栏*/editItem1= new JMenuItem("复制(C) Ctrl+C");editItem2= new JMenuItem("粘贴(P) Ctrl+V");editItem1.setFont(new Font("宋体",Font.PLAIN,12));editItem2.setFont(new Font("宋体",Font.PLAIN,12));/***查看栏*/seeItem1= new JRadioButtonMenuItem("科学型(T)");seeItem2= new JRadioButtonMenuItem("标准型(S)");seeItem3= new JCheckBoxMenuItem("数字分组(I)");seeItem1.setFont(new Font("宋体",Font.PLAIN,12));seeItem2.setFont(new Font("宋体",Font.PLAIN,12));seeItem3.setFont(new Font("宋体",Font.PLAIN,12));/***帮助栏*/help1 = new JMenuItem("帮助主题(H)");help2= new JMenuItem("关于计算器(A)");help1.setFont(new Font("宋体",Font.PLAIN,12));help2.setFont(new Font("宋体",Font.PLAIN,12));bgb = new ButtonGroup();//选项组menu1.add(editItem1);menu1.add(editItem2);menu2.add(seeItem1);menu2.add(seeItem2);menu2.addSeparator();//添加一条分割线menu2.add(seeItem3);menu3.add(help1);menu3.addSeparator();//添加一条分割线menu3.add(help2);myBar.add(menu1);myBar.add(menu2);myBar.add(menu3);this.setJMenuBar(myBar);numActionListener= new Num();//实现数字监听/***文本域,即为计算器的屏幕显示区域*/tf = new JTextField();tf.setEditable(false);//文本区域不可编辑tf.setBackground(Color.white);//文本区域的背景色tf.setHorizontalAlignment(JTextField.RIGH T);//文字右对齐tf.setText("0");tf.setBorder(BorderFactory.createLoweredB evelBorder());init();//对计算器进行初始化}/***初始化操作*添加按钮*/private void init(){addButton(panel1, "Backspace", newClear(), Color.red);addButton(panel1, "CE", new Clear(), Color.red);addButton(panel1, "C", new Clear(), Color.red);addButton(panel2, "1/x", new Signs(), Color.magenta);addButton(panel2, "log", new Signs(), Color.magenta);addButton(panel2, "7", numActionListener, Color.blue);addButton(panel2, "8", numActionListener, Color.blue);addButton(panel2, "9", numActionListener, Color.blue);addButton(panel2, "÷", new Signs(), Color.red);addButton(panel2, "n!", new Signs(), Color.magenta);addButton(panel2, "sqrt", new Signs(), Color.magenta);addButton(panel2, "4", numActionListener, Color.blue);addButton(panel2, "5", numActionListener, Color.blue);addButton(panel2, "6", numActionListener, Color.blue);addButton(panel2, "×", new Signs(), Color.red);addButton(panel2, "sin", new Signs(), Color.magenta);addButton(panel2, "x^2", new Signs(), Color.magenta);addButton(panel2, "1", numActionListener, Color.blue);addButton(panel2, "2", numActionListener, Color.blue);addButton(panel2, "3", numActionListener, Color.blue);addButton(panel2, "-", new Signs(), Color.red);addButton(panel2, "cos", new Signs(), Color.magenta);addButton(panel2, "x^3", new Signs(), Color.magenta);addButton(panel2, "0", numActionListener, Color.blue);addButton(panel2, "-/+", new Clear(), Color.blue);addButton(panel2, ".", new Dot(), Color.blue);addButton(panel2, "+", new Signs(), Color.red);addButton(panel2, "tan", new Signs(), Color.magenta);addButton(panel2, "%", new Signs(), Color.magenta);addButton(panel2, "π", numActionListener, Color.orange);addButton(panel2, "e", numActionListener, Color.orange);addButton(panel2, "′″", new Signs(), Color.orange);addButton(panel2, "=", new Signs(), Color.red);JButton btns = new JButton("计算器");btns.setBorder(BorderFactory.createLowere dBevelBorder());btns.setEnabled(false);//按钮不可操作btns.setPreferredSize(new Dimension(20, 20));panel3.add(btns);//加入按钮addButton(panel3, "MC", null, Color.red);addButton(panel3, "MR", null, Color.red);addButton(panel3, "MS", null, Color.red);addButton(panel3, "M+", null, Color.red);panel4.add(panel1,BorderLayout.NORTH);panel4.add(panel2,BorderLayout.CENTER);this.add(tf, BorderLayout.NORTH);this.add(panel3, BorderLayout.WEST);this.add(panel4);pack();this.setResizable(false);//窗口不可改变大小this.setLocation(300, 200);this.setDefaultCloseOperation(JFrame.EXIT _ON_CLOSE);}/***统一设置按钮的的使用方式*@param panel*@param name*@param action*@param color*/private void addButton(JPanel panel, String name, ActionListener action, Color color){JButton bt = new JButton(name);panel.add(bt);//在面板上增加按钮bt.setForeground(color);//设置前景(字体)颜色bt.addActionListener(action);//增加监听事件}/***计算器的基础操作(+-×÷)*@param x*/private void getResult (double x){if(oper == "+"){result += x;}else if(oper == "-"){result -= x;}else if(oper == "×"){result *= x;}else if(oper == "÷"){result /= x;}else if(oper == "="){result = x;}tf.setText(df.format(result));}/***运算符号的事件监听*/class Signs implements ActionListener{ public void actionPerformed(ActionEvent e) {/** 用ActionEvent对象的getActionCommand()方法* 取得与引发事件对象相关的字符串*/String str = e.getActionCommand();/* sqrt求平方根*/if(str.equals("sqrt")){double i = Double.parseDouble(tf.getText());if(i>=0){/** String.valueOf() 转换为字符串* df.format() 按要求保留四位小数* Math.sqrt() 求算数平方根*/tf.setText(String.valueOf(df.format(Math.sq rt(i))));}else{tf.setText("负数不能开平方根");}}/* log求常用对数*/else if(str.equals("log")){double i = Double.parseDouble(tf.getText());if(i>0){tf.setText(String.valueOf(df.format(Math.lo g(i))));}else{tf.setText("负数不能求对数");}}/* %求百分比*/else if(str.equals("%")){tf.setText(df.format(Double.parseDouble(tf. getText()) / 100));}/* 1/x求倒数*/else if(str.equals("1/x")){if(Double.parseDouble(tf.getText()) == 0){tf.setText("除数不能为零");}else{tf.setText(df.format(1 / Double.parseDouble(tf.getText())));}}/* sin求正弦函数*/else if(str.equals("sin")){double i = Double.parseDouble(tf.getText());tf.setText(String.valueOf(df.format(Math.si n(i))));}/* cos求余弦函数*/else if(str.equals("cos")){double i = Double.parseDouble(tf.getText());tf.setText(String.valueOf(df.format(Math.co s(i))));}/* tan求正切函数*/else if(str.equals("tan")){double i = Double.parseDouble(tf.getText());tf.setText(String.valueOf(df.format(Math.ta n(i))));}/* n!求阶乘*/else if(str.equals("n!")){double i = Double.parseDouble(tf.getText());if((i%2==0)||(i%2==1))//判断为整数放进行阶乘操作{int j = (int)i;//强制类型转换int result=1;for(int k=1;k<=j;k++)result *= k;tf.setText(String.valueOf(result));}else{tf.setText("无法进行阶乘");}}/* x^2求平方*/else if(str.equals("x^2")){double i = Double.parseDouble(tf.getText());tf.setText(String.valueOf(df.format(i*i)));}/* x^3求立方*/else if(str.equals("x^3")){double i =Double.parseDouble(tf.getText());tf.setText(String.valueOf(df.format(i*i*i)));}/* ′″角度转换*//***将角度值转换成弧度值,方便三角函数的计算*/else if(str.equals("′″")){double i = Double.parseDouble(tf.getText());tf.setText(String.valueOf(i/180*Math.PI));}else{if(flag){IfResult = false;}if(IfResult){oper = str;}else{getResult(Double.parseDouble(tf.getText()) );oper = str;IfResult = true;}}}}/***清除按钮的事件监听*/class Clear implements ActionListener{ public void actionPerformed(ActionEvent e) {/** 用ActionEvent对象的getActionCommand()方法* 取得与引发事件对象相关的字符串*/String str = e.getActionCommand();if(str == "C"){tf.setText("0");IfResult = true;result = 0;}else if(str == "-/+"){double i = 0 - Double.parseDouble(tf.getText().trim());tf.setText(df.format(i));}else if(str == "Backspace"){if(Double.parseDouble(tf.getText()) > 0){if(tf.getText().length() > 1){tf.setText(tf.getText().substring(0,tf.getText().length() - 1));//使用退格删除最后一位字符}else{tf.setText("0");IfResult = true;}}else{if(tf.getText().length() > 2){tf.setText(tf.getText().substring(0,tf.getText().length() - 1));}else{tf.setText("0");IfResult = true;}}}else if(str == "CE"){tf.setText("0");IfResult = true;}}}/***数字输入的事件监听*/class Num implements ActionListener{ public void actionPerformed(ActionEvent e) {String str = e.getActionCommand(); if(IfResult){tf.setText("");IfResult = false;}if(str=="π"){tf.setText(String.valueOf(Math.PI)); }else if(str=="e"){tf.setText(String.valueOf(Math.E)); }else{tf.setText(tf.getText().trim() + str);if(tf.getText().equals("0")){tf.setText("0");IfResult = true;flag = true;}}}}/***小数点的事件监听*/class Dot implements ActionListener{ public void actionPerformed(ActionEvent e) {IfResult = false;if(tf.getText().trim().indexOf(".") == -1){tf.setText(tf.getText() + ".");}}}/***main方法*/public static void main(String[] args) { new Calucator().setVisible(true);}}。
计算器JAVA源代码
import java.awt.*;import javax.swing.*;import java.awt.Event.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;public class Calculation extends JFrame implements ActionListener {private JTextField result;JTextField fm;Double dm = 0d;public Calculation(){super("计算器");result = new JTextField("0",30);result.setBackground(Color.white);result.setHorizontalAlignment(JTextField.RIGHT);result.setEditable(false);JPanel resultpanel = new JPanel();resultpanel.add(result);fm = new JTextField(2);JButton b1= new JButton("Backspace");JButton b2= new JButton("CE");JButton b3= new JButton("C");JPanel ControalPanel = new JPanel();ControalPanel.setLayout(new GridLayout(1,4,2,2));ControalPanel.add(fm);ControalPanel.add(b1);ControalPanel.add(b2);ControalPanel.add(b3);b1.addActionListener(this);b2.addActionListener(this);b3.addActionListener(this);String dckey [] = {"MC","0","1","2","3","4","5","6","7","8","9","/","sqrt","MR","*","%","MS","-","1/x","M+","+/-" ,".","+","="};JPanel dckeypanel =new JPanel();dckeypanel.setLayout(new GridLayout(4,6,2,2));for(int i=0;i<24;i++){JButton b = new JButton(dckey[i]);dckeypanel.add(b);b.addActionListener(this);}Container ct = this.getContentPane();ct.setLayout(new BorderLayout());ct.add(resultpanel,BorderLayout.NORTH);ct.add(ControalPanel,BorderLayout.CENTER);ct.add(dckeypanel,BorderLayout.SOUTH);pack();setVisible(true);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);}private boolean newDigital = true;private int optionvalue;private String operation = "";private Double d,d1,d2;public void actionPerformed(ActionEvent e){String s = (e.getActionCommand());String str = result.getText();if(s.equals("Backspace")){String s1 = result.getText();result.setText(s1.substring(0,s1.length()-1));}if(s.equals("CE")){result.setText("0");newDigital = true;}if(s.equals("C")){result.setText("0");optionvalue = 0;newDigital = true;}if(s.equals("0")||s.equals("1")||s.equals("2")||s.equals("3")||s.equals("4")||s.equals("5")||s.equal s("6")||s.equals("7")||s.equals("8")||s.equals("9")){if(!newDigital){result.setText(str+s);}else{result.setText(s);newDigital = false;}return;}if(s.equals(".")){if(result.getText().trim().startsWith("0")){result.setText("0.");newDigital = false;}else{result.setText(str+".");}return;}if(s.equals("+/-")){d = Double.parseDouble(str.trim());result.setText(String.valueOf((-d)));return;}if(s.equals("+")){d1 = Double.parseDouble(result.getText());optionvalue = 1;result.setText("");}if(s.equals("-")){d1 = Double.parseDouble(result.getText());optionvalue = 2;result.setText("");}if(s.equals("*")){d1 = Double.parseDouble(result.getText());optionvalue = 3;result.setText("");}if(s.equals("/")){d1 = Double.parseDouble(result.getText());optionvalue = 4;result.setText("");}if(s.equals("=")){d2 = Double.parseDouble(result.getText());switch(optionvalue){case 1:result.setText(String.valueOf(d1+d2));break;case 2:result.setText(String.valueOf(d1-d2));break;case 3:result.setText(String.valueOf(d1*d2));break;case 4:if(d2!=0){result.setText(String.valueOf(d1/d2));}else{result.setText("除数不能为零");return;}break;}operation = "";}if(s.equals("sqrt")){d = Double.parseDouble(result.getText().trim());if(d>=0){result.setText(String.valueOf((Math.sqrt(d))));}else{result.setText("除数不能为零");}}if(s.equals("1/x")){d = Double.parseDouble(result.getText().trim());if(str.equals("0")){result.setText("除数不能为零");}else{result.setText(String.valueOf((1/d)));}}if(s.equals("%")){result.setText(String.valueOf((Double.parseDouble(str)/100))); }if(s.equals("MC")){fm.setText("");dm=0d;newDigital = true;}if(s.equals("MR")){if(fm.getText().trim()!=""){result.setText(""+dm);}}if(s.equals("MS")){dm = Double.parseDouble(result.getText().trim());fm.setText("M");}if(s.equals("M+")){dm = dm+Double.parseDouble(result.getText().trim());}}public static void main (String [] args){ new Calculation();}}。
计算器完整代码(java)
1. Calculator 类import java.applet.*;import java.awt.*;import java.awt.event.*;import ng.*;import java.applet.Applet;import javax.swing.*;import javax.swing.border.*;public class Calculator extends JApplet 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"};private final String[] M={" ","MC","MR","MS","M+"};private JButton keys[]=new JButton[KEYS.length];private JButton commands[]=new JButton[COMMAND.length];private JButton m[]=new JButton[M.length];private JTextField display =new JTextField("0");// public JTextField setHorizontalAlignment(int alignment);// private JTextFielddisplay.setHorizontalAlignment(JTextField.RIGHT)=new JTextField("0"); private void setup(){display.setHorizontalAlignment(JTextField.RIGHT);JPanel calckeys=new JPanel();JPanel command=new JPanel();JPanel calms=new JPanel();calckeys.setLayout(new GridLayout(4,5,3,3));command.setLayout(new GridLayout(1,3,3,3));calms.setLayout(new GridLayout(5,1,3,3));for(int i=0;i<KEYS.length;i++){keys[i]=new JButton(KEYS[i]);calckeys.add(keys[i]);keys[i].setForeground(Color.blue);}keys[3].setForeground(Color.red);keys[4].setForeground(Color.red);keys[8].setForeground(Color.red);keys[9].setForeground(Color.red);keys[13].setForeground(Color.red);keys[14].setForeground(Color.red);keys[18].setForeground(Color.red);keys[19].setForeground(Color.red);for(int i=0;i<COMMAND.length;i++){commands[i]=new JButton(COMMAND[i]);command.add(commands[i]);commands[i].setForeground(Color.red);}for(int i=0;i<M.length;i++){m[i]=new JButton(M[i]);calms.add(m[i]);m[i].setForeground(Color.red);}JPanel panel1=new JPanel();panel1.setLayout(new BorderLayout(3,3));panel1.add("North",command);panel1.add("Center",calckeys);JPanel top=new JPanel();top.setLayout(new BorderLayout());display.setBackground(Color.WHITE);top.add("Center",display);getContentPane().setLayout(new BorderLayout(3,5)); getContentPane().add("North",top);getContentPane().add("Center",panel1); getContentPane().add("West",calms);}public void init(){setup();for(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);}display.setEditable(false);}public void actionPerformed(ActionEvent e){String label=e.getActionCommand();// double zero=e.getActionCommand();if(label=="C")handleC();else if(label=="Backspace")handleBackspace();else if(label=="CE")display.setText("0");else if (label=="1/x")daoShu();else if(label=="sqrt"){display.setText(Math.sqrt(getNumberFromDisplay())+"");}else if("0123456789.".indexOf(label)>=0){handleNumber(label);// handlezero(zero);}elsehandleOperator(label);}private boolean firstDigit=true;private void handleNumber(String key){if(firstDigit){ if(key.equals("0"))display.setText(key);else if(key.equals(".")){display.setText("0.");firstDigit=false;}else if(!key.equals("0")&&!key.equals(".")){display.setText(key);firstDigit=false;}}else if((key.equals("."))&&(display.getText().indexOf(".")<0)) display.setText(display.getText()+".");else if(!key.equals(".")&&display.getText().length()<=32) display.setText(display.getText()+key);}private double number=0;private String operator="=";private void handleOperator(String key){if(operator.equals("/")){if(getNumberFromDisplay()==0){display.setText("除数不能为零");}else{number/=getNumberFromDisplay();}long t1;double t2;t1=(long)number;t2=number-t1;if(t2==0){display.setText(String.valueOf(t1));}else{display.setText(String.valueOf(number));}}else if(operator.equals("+"))number+=getNumberFromDisplay();else if(operator.equals("-"))number-=getNumberFromDisplay();else if(operator.equals("*"))number*=getNumberFromDisplay();else if(operator.equals("%"))number=number/100;else if(operator.equals("+/-"))number=number*(-1);else if(operator.equals("="))number=getNumberFromDisplay();long t1;double t2;t1=(long)number;t2=number-t1;if(t2==0)display.setText(String.valueOf(t1));elsedisplay.setText(String.valueOf(number));operator=key;firstDigit=true;}private double getNumberFromDisplay(){return Double.valueOf(display.getText()).doubleValue(); }private void handleC(){display.setText("0");firstDigit=true;operator="=";}private void handleBackspace(){String text=display.getText();int i=text.length();if(i>0){text=text.substring(0,i-1);if(text.length()==0){display.setText("0");firstDigit=true;operator="=";}elsedisplay.setText(text);}}private void daoShu(){if (display.getText().equals("0")){display.setText("除数不能为零");System.out.println(1);}else{long l;double d=1/getNumberFromDisplay();l=(long)d;System.out.println(d);System.out.println(l);display.setText(String.valueOf(d));}}}2.CalFrame 类import java.awt.Color;importimport java.awt.event.ActionListener;import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;import javax.swing.JApplet;import javax.swing.JFrame;public class Test {public static void main(String[] args) {JFrame f=new JFrame();f.getAccessibleContext();Calculator Calculator1=new Calculator(); Calculator1.init();f.getContentPane().add("Center",Calculator1);f.setVisible(true);f.setBounds(300, 200,380,245);f.setBackground(Color.LIGHT_GRAY);f.validate();f.setResizable(false);f.addWindowListener(new WindowAdapter(){public void windowClosing(WindowEvent e){System.exit(0);}});f.setTitle("计算器");}}。
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编写的计算器(Calculator)
用java编写的计算器(Calculator)import java.io.*;import java.awt.*;import java.awt.event.*;import java.util.*;public class Calculator{public static void main(String[] args){new MyfirstCalculator();}}class MyfirstCalculator{Frame f=new Frame("calculator");TextField tf=new T extField(50);ArrayList sa=new ArrayList();//sa用来存储sb中的数据StringBuilder sb=new StringBuilder();//sb用来存储0-9中的数据StringBuilder sb1=new StringBuilder();//用作判断,里面数据为:+,-,*,/四个中的任意一个或多个StringBuilder sb2=new StringBuilder();//用作判断,里面数据为:=MyfirstCalculator(){init();}public void init(){Button b0=new Button("0");Button b1=new Button("1");Button b2=new Button("2");Button b3=new Button("3");Button b4=new Button("4");Button b5=new Button("5");Button b6=new Button("6");Button b7=new Button("7");Button b8=new Button("8");Button b9=new Button("9");Button ba=new Button("=");Button bb=new Button("-");Button bc=new Button("+");Button bd=new Button("*");Button be=new Button("/");//Button bf=new Button("D");//定义一个清空按钮,用来从头开始计数f.add(tf);f.add(b0);f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);f.add(b6);f.add(b7);f.add(b8);f.add(b9);f.add(ba);f.add(bb);f.add(bc);f.add(bd);f.add(be);//f.add(bf);f.setBounds(400,400,300,300);f.setVisible(true);f.setLayout(new GridLayout(4,4));//下面的b[0-9]为按钮事件,让点击的按钮数字能够在TextField(tf)中能够显示b0.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){if(sb2.indexOf("=")!=-1){sb.delete(0,sb.length());//在按"="之后在按0-9之间的数字,就清空sb 中的数据,从头开始计数}tf.setText("");sb.append(0);//点击数字按钮,就在sb中加一个数字;tf.setText(sb.toString());//在tf中显示按钮所输入的数字}});b1.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e) //下面同b0判断的方法一样{if(sb2.indexOf("=")!=-1){sb.delete(0,sb.length());}tf.setText("");sb.append("1");tf.setText(sb.toString());}});b2.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e) //下面同b0判断的方法一样{if(sb2.indexOf("=")!=-1){sb.delete(0,sb.length());}tf.setText("");sb.append("2");tf.setText(sb.toString());}});b3.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e) //下面同b0判断的方法一样{if(sb2.indexOf("=")!=-1){sb.delete(0,sb.length());}tf.setText("");sb.append("3");tf.setText(sb.toString());}});b4.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e) //下面同b0判断的方法一样{if(sb2.indexOf("=")!=-1){sb.delete(0,sb.length());}tf.setText("");sb.append("4");tf.setText(sb.toString());}});b5.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e) //下面同b0判断的方法一样{if(sb2.indexOf("=")!=-1){sb.delete(0,sb.length());}tf.setText("");sb.append("5");tf.setText(sb.toString());}});b6.addActionListener(new ActionListener()public void actionPerformed(ActionEvent e) //下面同b0判断的方法一样{if(sb2.indexOf("=")!=-1){sb.delete(0,sb.length());}tf.setText("");sb.append("6");tf.setText(sb.toString());}});b7.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e) //下面同b0判断的方法一样{if(sb2.indexOf("=")!=-1){sb.delete(0,sb.length());}tf.setText("");sb.append("7");tf.setText(sb.toString());}});b8.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e) //下面同b0判断的方法一样{if(sb2.indexOf("=")!=-1)sb.delete(0,sb.length());}tf.setText("");sb.append("8");tf.setText(sb.toString());}});b9.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e) //下面同b0判断的方法一样{if(sb2.indexOf("=")!=-1){sb.delete(0,sb.length());}sb.append("9");tf.setText(sb.toString());}});//bc在此处为"+"事件,调动"-"(bb),"*"(bd),"/"(be)这三个中的其中一个算法bc.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){sa.add(sb.toString());//把sb中的数据即tf(TextField)中显示的数据添加到sa 集合中,用于做加减乘除运算sb.delete(0,sb.length());//清空sb中的缓存,以便于sb存入tf中显示的下一个数字sb1.append("+");//当点击"="按钮,"+"用作加法运算判断的标志sb2.delete(0,sb2.length());//清空sb2中的数据/*//此处为加法运算,--测试代码if(sb1.indexOf("+")!=-1)){int sum=0;for(String s:sa){sum+=Integer.parseInt(s);}//sb1.append("+");System.out.println("+2..."+sum);sa.clear();sa.add(""+sum);System.out.println(sa);tf.setText(""+sum);//sa.add(sb.toString());System.out.println("+..."+sa);sb.delete(0,sb.length());sb1.delete(0,sb1.length());sb1.append("+");}*///此处为减法运算if(sb1.indexOf("-")!=-1){int sum=0;int count=0;for(String s:sa){if(count==0){sum=Integer.parseInt(s);//System.out.println(""+sum);--测试代码} else{sum+=-(Integer.parseInt(s));}count++;}//System.out.println("-2..."+sum);--测试代码sa.clear();sa.add(""+sum);//System.out.println(sa);--测试代码tf.setText(""+sum);//System.out.println("-..."+sa);--测试代码sb.delete(0,sb.length());sb1.delete(0,sb1.length());sb1.append("+");}//此处为乘法运算if(sb1.indexOf("*")!=-1){int sum=1;for(String s:sa){sum=sum*Integer.parseInt(s);}//System.out.println("*2..."+sum);--测试代码sa.clear();sa.add(""+sum);//System.out.println(sa);--测试代码tf.setText(""+sum);//System.out.println("*..."+sa);--测试代码sb.delete(0,sb.length());sb1.delete(0,sb1.length());sb1.append("+");}//此处为除法运算if(sb1.indexOf("/")!=-1){int sum=0;int count=0;for(String s:sa){if(count==0){sum=Integer.parseInt(s);}else{sum/=Integer.parseInt(s);}count++;}//System.out.println("-2..."+sum);--测试代码sa.clear();sa.add(""+sum);//System.out.println(sa);--测试代码tf.setText(""+sum);//System.out.println("/..."+sa);--测试代码sb.delete(0,sb.length());sb1.delete(0,sb1.length());sb1.append("+");}}});//ba在此处为"="事件,调动"-"(bb),"+"(ba),"*"(bd),"/"(be),这四个中的其中一个算法ba.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e){if(sa.size()==0)//当sa集合中没有元素,即就没有任何数字用于做加减乘除运算,就中断程序return;if(sb1.indexOf("+")!=-1)//加法运算判断{sa.add(sb.toString());//System.out.println("+1..."+sa);--测试代码int sum=0;for(String s:sa){sum+=Integer.parseInt(s);}//System.out.println(""+sum);--测试代码tf.setText(""+sum);//把算出的结果显示在tf中sa.clear();//清空集合中的元素,以便于做下一个运算sb.delete(0,sb.length());sb.append(""+sum);//当点击"="按钮后,再点击"-","+","*","/"中的任意一个按钮,就要把结果存入到sa集合中,用与下一个数字做运算//sa.append(""+sum);--测试代码sb1.delete(0,sb1.length());sb2.append("=");}if(sb1.indexOf("-")!=-1)//减法运算判断{sa.add(sb.toString());System.out.println("-1..."+sa);int sum=0;int count=0;for(String s:sa){if(count==0){sum=Integer.parseInt(s);//System.out.println(""+sum);--测试代码}else{sum+=-(Integer.parseInt(s));}count++;}//System.out.println(""+sum);--测试代码tf.setText(""+sum);sb.delete(0,sb.length());sb.append(""+sum);sa.clear();sb1.delete(0,sb1.length());sb2.append("=");}if (sb1.indexOf("*")!=-1)//乘法运算判断{ sa.add(sb.toString());//System.out.println("*1..."+sa);int sum=1;for(String s:sa){sum=sum*Integer.parseInt(s);}//System.out.println(""+sum);--测试代码tf.setText(""+sum);sb.delete(0,sb.length());sa.clear();sb.append(""+sum);sb1.delete(0,sb1.length());sb2.append("=");}if(sb1.indexOf("/")!=-1)//除法运算判断{sa.add(sb.toString());System.out.println("/.."+sa);int sum=0;int count=0;for(String s:sa){if(count==0){sum=Integer.parseInt(s);}else{sum/=Integer.parseInt(s);}count++;}//System.out.println(""+sum);--测试代码tf.setText(""+sum);sb.delete(0,sb.length());sa.clear();sb.append(""+sum);sb2.append("=");}sb1.delete(0,sb1.length());}});//bb在此处为"-"事件,调动"+"(bc),"*"(bd),"/"(be)这三个中的其中一个算法bb.addActionListener(new ActionListener() //下面同bc("+")事件判断的方法一样{public void actionPerformed(ActionEvent e){sa.add(sb.toString());System.out.println("-..."+sa);sb.delete(0,sb.length());sb1.append("-");sb2.delete(0,sb2.length());if(sb1.indexOf("+")!=-1){int sum=0;for(String s:sa){sum+=Integer.parseInt(s);}//System.out.println("+2..."+sum);--测试代码sa.clear();sa.add(""+sum);//System.out.println(sa);--测试代码tf.setText(""+sum);//System.out.println("+..."+sa);--测试代码sb.delete(0,sb.length());sb1.delete(0,sb1.length());sb1.append("-");}/*--测试代码if(sb1.indexOf("-")!=-1){int sum=0;int count=0;for(String s:sa){if(count==0){sum=Integer.parseInt(s);//System.out.println(""+sum);}else{sum+=-(Integer.parseInt(s));}count++;}sb1.append("-");System.out.println("-2..."+sum);sa.clear();sa.add(""+sum);System.out.println(sa);tf.setText(""+sum);sa.add(sb.toString());System.out.println("*..."+sa);sb.delete(0,sb.length());sb1.delete(0,sb1.length());sb1.append("/");}*/if(sb1.indexOf("*")!=-1){int sum=1;for(String s:sa){sum=sum*Integer.parseInt(s);}//System.out.println("*2..."+sum);--测试代码sa.clear(); sa.add(""+sum);//System.out.println(sa);--测试代码tf.setText(""+sum);//System.out.println("*..."+sa);--测试代码sb.delete(0,sb.length());sb1.delete(0,sb1.length());sb1.append("-");}if(sb1.indexOf("/")!=-1){int sum=0;int count=0;for(String s:sa){if(count==0){sum=Integer.parseInt(s);}else{sum/=Integer.parseInt(s);}count++;}//System.out.println("-2..."+sum);--测试代码sa.clear();sa.add(""+sum);//System.out.println(sa);--测试代码tf.setText(""+sum);//System.out.println("-..."+sa);--测试代码sb.delete(0,sb.length());sb1.delete(0,sb1.length());sb1.append("-");}}});//bd在此处为"*"事件,调动"-"(bb),"+"(bc),"/"(be)这三个中的其中一个算法bd.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e) //下面同bc("+")事件判断的方法一样{sa.add(sb.toString());sb.delete(0,sb.length());sb1.append("*");sb2.delete(0,sb2.length());if(sb1.indexOf("+")!=-1){int sum=0;for(String s:sa){sum+=Integer.parseInt(s);}//System.out.println("+2..."+sum);--测试代码sa.clear();sa.add(""+sum);//System.out.println(sa);--测试代码tf.setText(""+sum);//System.out.println("*..."+sa);--测试代码sb.delete(0,sb.length());sb1.delete(0,sb1.length());sb1.append("*");}if(sb1.indexOf("-")!=-1){int sum=0;int count=0;for(String s:sa){if(count==0){sum=Integer.parseInt(s);//System.out.println(""+sum);--测试代码} else{sum+=-(Integer.parseInt(s));}count++;}//System.out.println("-2..."+sum);--测试代码sa.clear();sa.add(""+sum);//System.out.println(sa);--测试代码tf.setText(""+sum);//System.out.println("*..."+sa);--测试代码sb.delete(0,sb.length());sb1.delete(0,sb1.length());sb1.append("*");}if(sb1.indexOf("/")!=-1){int sum=0;int count=0;for(String s:sa){if(count==0){sum=Integer.parseInt(s);}else{sum/=Integer.parseInt(s);}count++;}//System.out.println("/2..."+sum);--测试代码sa.clear();sa.add(""+sum);//System.out.println(sa);--测试代码tf.setText(""+sum);//System.out.println("*..."+sa);--测试代码sb.delete(0,sb.length());sb1.delete(0,sb1.length());sb1.append("*");}/*--测试代码int sum=1;for(String s:sa){sum=sum*Integer.parseInt(s);}sb1.append("*");System.out.println(""+sum);tf.setText(""+sum);*/}//be在此处为"/"事件,调动"-"(bb),"*"(bd),"+"(bc)这三个中的其中一个算法be.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e) //下面同bc("+")事件判断的方法一样{sa.add(sb.toString());System.out.println("+.."+sa);sb.delete(0,sb.length());sb1.append("+");//sb2.delete(0,sb2.length());if(sb1.indexOf("+")!=-1){int sum=0;for(String s:sa){sum+=Integer.parseInt(s);}sa.clear();sa.add(""+sum);//System.out.println(sa);--测试代码tf.setText(""+sum);//System.out.println("*..."+sa);--测试代码sb.delete(0,sb.length());sb1.delete(0,sb1.length());sb1.append("/");}if(sb1.indexOf("-")!=-1)int sum=0;int count=0;for(String s:sa){if(count==0){sum=Integer.parseInt(s);//System.out.println(""+sum);--测试代码} else{sum+=-(Integer.parseInt(s));}count++;}//System.out.println("-2..."+sum);--测试代码sa.clear();sa.add(""+sum);//System.out.println(sa);--测试代码tf.setText(""+sum);//System.out.println("*..."+sa);--测试代码sb.delete(0,sb.length());sb1.delete(0,sb1.length());sb1.append("/");}if(sb1.indexOf("*")!=-1){int sum=1;for(String s:sa){sum=sum*Integer.parseInt(s);}sa.clear();sa.add(""+sum);//System.out.println(sa);--测试代码tf.setText(""+sum);//System.out.println("*..."+sa);--测试代码sb.delete(0,sb.length());sb1.delete(0,sb1.length());sb1.append("/");}/*--测试代码int sum=0;int count=0;for(String s:sa){if(count==0){sum=Integer.parseInt(s);}else{sum/=Integer.parseInt(s);}count++;}System.out.println(""+sum);sb1.append("/");tf.setText(""+sum);*/}});//定义一个清除器事件,清空所用数据用--测试代码/* bf.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) {sb.delete(0,sb.length());}});*///关闭窗口f.addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent e) {System.exit(0);}});}}。
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("计算器");}}。
超级简单明了的JAVA计算器代码
package caculator;import java.awt.Color;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.*;public class caculator extends JFrame implements ActionListener { double sum=0;static double getValue;static int action ;int i=0,j=0,p=0,l;double par1;JButton Jk=new JButton("k");JButton J1 = new JButton("1");JButton J2 = new JButton("2");JButton J3 = new JButton("3");JButton J4 = new JButton("4");JButton J5 = new JButton("5");JButton J6 = new JButton("6");JButton J7 = new JButton("7");JButton J8 = new JButton("8");JButton J9 = new JButton("9");JButton J0 = new JButton("0");JButton Je = new JButton("=");JButton Ja = new JButton("+");JButton Jr = new JButton("-");JButton Jm = new JButton("*");JButton Jd = new JButton("/");JButton Jc = new JButton("清除");JButton Jpt = new JButton(".");JTextArea show = new JTextArea("");caculator(){super("caculator");setLocation(200,200);setSize(300,350);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true);JPanel jp = new JPanel();jp.setLayout(null);jp.add(J1);jp.add(J2);jp.add(J3);jp.add(J4);jp.add(J5);jp.add(J6);jp.add(J7);jp.add(J8);jp.add(J9);jp.add(J0);jp.add(Je);jp.add(Ja);jp.add(Jr);jp.add(Jm);jp.add(Jd);jp.add(Jc);jp.add(Je);jp.add(Jpt);J9.setBackground(Color.pink); J8.setBackground(Color.pink); J7.setBackground(Color.pink); J6.setBackground(Color.pink); J5.setBackground(Color.pink); J4.setBackground(Color.pink); J3.setBackground(Color.pink); J2.setBackground(Color.pink); J1.setBackground(Color.pink); J0.setBackground(Color.pink);Je.setBackground(Color.pink);Ja.setBackground(Color.pink); Jr.setBackground(Color.pink); Jm.setBackground(Color.pink); Jd.setBackground(Color.pink); Jc.setBackground(Color.pink); Jpt.setBackground(Color.pink);J7.setBounds(10,70,60,50);J8.setBounds(75,70,60,50);J9.setBounds(140,70,60,50); J4.setBounds(10,125,60,50); J5.setBounds(75,125,60,50); J6.setBounds(140,125,60,50); J1.setBounds(10,180,60,50); J2.setBounds(75,180,60,50); J3.setBounds(140,180,60,50); J0.setBounds(10,235,60,50); Je.setBounds(75,235,60,50); Jpt.setBounds(140,235,60,50);Jd.setBounds(205,70,60,50); Jm.setBounds(205,125,60,50); Jr.setBounds(205,180,60,50); Ja.setBounds(205,235,60,50); Jc.setBounds(205,10,60,50);J1.addActionListener(this);J2.addActionListener(this);J3.addActionListener(this);J4.addActionListener(this);J5.addActionListener(this);J6.addActionListener(this);J7.addActionListener(this);J8.addActionListener(this);J9.addActionListener(this);J0.addActionListener(this);Ja.addActionListener(this);Jr.addActionListener(this);Jm.addActionListener(this);Je.addActionListener(this);Jc.addActionListener(this);Jpt.addActionListener(this);jp.add(show);show.setBackground(Color.pink);show.setBounds(10,10,180,50);setContentPane(jp);}@Overridepublic void actionPerformed(ActionEvent e) { if(e.getSource()==J0){show.setText("0"); }if(e.getSource()==J1){show.setText("1");}if(e.getSource()==J2){show.setText("2");}if(e.getSource()==J3){show.setText("3");}if(e.getSource()==J4){show.setText("4");}if(e.getSource()==J5){show.setText("5");}if(e.getSource()==J6){show.setText("6");}if(e.getSource()==J7){show.setText("7");}if(e.getSource()==J8){show.setText("8");}if(e.getSource()==J9){show.setText("9");}par1=Double.parseDouble(show.getText()); if(e.getSource()==Ja){show.setText("");if(j==0){sum=par1;}else if(action==1){sum+=par1;}setsum();j++;p=0;i=0;action = 1;} if(e.getSource()==Jr){show.setText("");if(j==0){sum=par1;}else if(action==2){sum-=par1;}setsum();j++;p=0;i=0;action = 2;}if(e.getSource()==Jm){show.setText(""); if(j==0){sum=par1;}else if(action==3){sum*=par1;}setsum();j++;p=0;i=0;action = 3;}if(e.getSource()==Jd){show.setText(""); if(j==0){sum=par1;}else if(action==4){sum/=par1;}setsum();j++;p=0;i=0;action = 4;if(e.getSource()==Jc){clear();}if(e.getSource()==Jpt){show.append(".");}if(e.getSource()==Je){switch(action){case 1:show.setText(String.valueOf(sum+=par1)); break;case 2:show.setText(String.valueOf(sum-=par1)); break;case 3:show.setText(String.valueOf(sum*=par1)); break;case 4:show.setText(String.valueOf(sum/=par1)); break;}i=0;j=0;action=0;}}private void setsum() {show.setText(String.valueOf(sum));String s=show.getText();}void clear(){i=0;j=0;p=0;sum=0;action=0;show.setText("0"); }// TODO Auto-generated method stubpublic static void main(String args[]){caculator ct=new caculator();}}。
计算器(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模拟科学计算器
import java.awt.*;import java.awt.event.*;import javax.swing.*;public class Ca extends JFrame implements ActionListener{//*********************************************************************** //标准型计算器控件键钮static JFrame f1 = new JFrame("计算器");private String KEYS[] = {"7","8","9","/","sqrt","4","5","6","*","%","1","2","3","-","1/x","0","+/-",".","+","="};private String M[] = {" ","MC","MR","MS","M+"};private String COM[] = {"Backspace","CE","C"};private JButton keys[] = new JButton[KEYS.length];private JButton com[] = new JButton[COM.length];private JButton m[] = new JButton[M.length];private JTextField result,hh,jj;MenuBar menubar1=new MenuBar();Menu edit=new Menu("编辑(E)"),view=new Menu("查看(V)"),help=new Menu("帮助(H)");MenuItem copy=new MenuItem("复制(C)"),paste=new MenuItem("粘贴(P)"),standar=new MenuItem("标准型(T)"),science=new MenuItem("科学型(S)"),numgroup=new MenuItem("数字分组(I)"),helpt=new MenuItem("帮助主题(H)"),about=new MenuItem("关于计算器(A)");private boolean firstDigit = true; //判断第一个输入的字符是否是数字private double resultNum = 0.0,resultNum2 = 0.0; //中间结果private String operator = "=",co,str,operator2 = "=";private boolean operateValidFlag = true;//*********************************************************************** //科学性计算器控件及按钮static JFrame f2 = new JFrame("科学计算器");private JTextField result2;private String[] KON = {"sta","F-E","(",")","MC","Ave","dms","Exp","In","MR","Sum","sin","x^y","log","MS","s","cos","x^3","n!","M+","Dat","tan","x^2","1/x","pi"};private String[] KO = {"7","8","9","/","Mod","And","4","5","6","*","Or","Xor","1","2","3","-","Lsh","Not","0","+/-",".","+","=","Int","A","B","C","D","E","F"};private String ITM[]={"标准型","科学型","十六进制数(H) F5","十进制(D) F6","八进制(O) F7","二进制(B) F8","四字(Q) F12","DWORD 值(R)F2","单字(W)F3","字节(Y) F4","数字分组(I)"};private final String[] COMM = {"Backspace","CE","C"};private JButton comm[] = new JButton[COMM.length];private JButton kon[] = new JButton[KON.length];private JButton ko[] = new JButton[KO.length];private MenuItem itm[] = new MenuItem[ITM.length];private JPanel panel0,panel1,panel2,panel3,panel4,panel5,panel6;Checkbox checkbox1,checkbox2,checkbox3,checkbox4;MenuBar menubar2=new MenuBar(); //添加菜单条Menu edit2=new Menu("编辑(E)"),view2=new Menu("查看(V)"),help2=new Menu("帮助(H)");MenuItem copy2=new MenuItem("复制(C) Ctrl+C"),past2=new MenuItem("粘贴(P) Ctrl+V"),standar2=new MenuItem("标准型(T)"),science2=new MenuItem("科学型(S)"),numgroup2=new MenuItem("数字分组(I)"),menuitem1=new MenuItem("十六进制数(H) F5"),menuitem2=new MenuItem("十进制(D) F6"),menuitem3=new MenuItem("八进制(O) F7"),menuitem4=new MenuItem("二进制(B) F8"),menuitem5=new MenuItem("四字(Q) F12"),menuitem6=new MenuItem("DWORD 值(R)F2"),menuitem7=new MenuItem("单字(W)F3"),menuitem8=new MenuItem("字节(Y) F4"),helpt2=new MenuItem("帮助主题(H)"),about2=new MenuItem("关于计算器(A)");//*********************************************************************** //构造函数public Ca(){//标准型开始初始化********************result = new JTextField("0.");result.setHorizontalAlignment(JTextField.RIGHT); //文字右对齐result.setEditable(false); //设置为不可编辑result.setBackground(Color.WHITE); //设置颜色为白色JPanel k0 = new JPanel();k0.setLayout(new GridLayout(4,5,5,5));for(int i = 0;i < KEYS.length;i++){keys[i] = new JButton(KEYS[i]);k0.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 c0 = new JPanel();c0.setLayout(new GridLayout(1,3,5,5));for(int i = 0;i < COM.length;i++){com[i] = new JButton(COM[i]);c0.add(com[i]);com[i].setForeground(Color.red);}JPanel m0 = new JPanel();m0.setLayout(new GridLayout(5,1,5,5));for(int i = 0;i < M.length;i++){m[i] = new JButton(M[i]);m0.add(m[i]);m[i].setForeground(Color.red);}m[0].setForeground(Color.black);//f1的监视器for(int i = 0;i < KEYS.length;i++){keys[i].addActionListener(this);}for(int i = 0;i < COM.length;i++){com[i].addActionListener(this);}for(int i = 0;i < M.length;i++){m[i].addActionListener(this);}//复制事件copy.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){int count;count=str.length();if(count!=0)co=result.getText();elseSystem.out.println("没有可复制的对象");}});//粘贴事件paste.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){str=co;result.setText(str);}});//复制事件copy2.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){int count;count=str.length();if(count!=0)co=result2.getText();elseSystem.out.println("没有可复制的对象");}});//粘贴事件past2.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){str=co;result2.setText(str);}});edit.add(copy);edit.add(paste);view.add(standar);view.add(science);view.addSeparator();view.add(numgroup);help.add(helpt);help.addSeparator();help.add(about);menubar1.add(edit);menubar1.add(view);menubar1.add(help);//整体布局JPanel p1 = new JPanel();p1.setLayout(new BorderLayout());p1.add("North",c0);p1.add("Center",k0);JPanel p2 = new JPanel();p2.setLayout(new BorderLayout());p2.add("Center",result);f1.setLayout(new BorderLayout(3,5));f1.add("North",p2);f1.add("Center",p1);f1.add("West",m0);f1.setBackground(Color.LIGHT_GRAY);f1.setLocation(200,200);f1.setMenuBar(menubar1);f1.setVisible(true);f1.setResizable(false);//不可最大化f1.pack(); //紧凑f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//标准型初始化结束//**************************************************** standar2.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){f1.setVisible(true);f2.setVisible(false); //按钮不可操作}});science.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){f1.setVisible(false);f2.setVisible(true); //按钮不可操作}});//****************************************************//科学性初始化开始panel0=new JPanel();panel1=new JPanel();panel2=new JPanel();panel3=new JPanel();panel4=new JPanel();panel5=new JPanel();panel6=new JPanel();panel0.setLayout(new GridLayout(1,4)); //设置网格型布局管理器panel1.setLayout(new GridLayout(1,3,30,0));panel2.setLayout(new GridLayout(1,2));panel3.setLayout(new GridLayout(1,3,5,0));panel4.setLayout(new GridLayout(5,5,5,5));panel5.setLayout(new GridLayout(5,6,5,5));panel6.setLayout(new FlowLayout(FlowLayout.LEFT)); //按钮左对齐result2 = new JTextField("0.",100);result2.setHorizontalAlignment(JTextField.RIGHT); //文字右对齐result2.setEditable(false); //设置为文本不可编辑result2.setBackground(Color.WHITE); //设置文本框颜色为白色CheckboxGroup cbg1=new CheckboxGroup();checkbox1=new Checkbox("十六进制",false,cbg1);checkbox2=new Checkbox("十进制",true,cbg1);checkbox3=new Checkbox("八进制",false,cbg1);checkbox4=new Checkbox("二进制",false,cbg1);panel0.add(checkbox1);panel0.add(checkbox2);panel0.add(checkbox3);panel0.add(checkbox4);CheckboxGroup cbg2=new CheckboxGroup();panel1.add(new Checkbox("角度",true,cbg2));panel1.add(new Checkbox("弧度",false,cbg2));panel1.add(new Checkbox("梯度",false,cbg2));JLabel HH = new JLabel(" ");panel2.add(new Checkbox("Inv",false));panel2.add(new Checkbox("Hyp",false));hh = new JTextField();jj = new JTextField();hh.setText(" ");hh.setEditable(false);jj.setText(" ");jj.setEditable(false);panel2.add(hh);panel2.add(HH);panel2.add(jj);panel6.add(result2);edit2.add(copy2);edit2.add(past2);view2.add(standar2);view2.add(science2);view2.addSeparator();view2.add(menuitem1);view2.add(menuitem2);view2.add(menuitem3);view2.add(menuitem4);view2.addSeparator();view2.add(menuitem5);view2.add(menuitem6);view2.add(menuitem7);view2.add(menuitem8);view2.addSeparator();view2.add(numgroup2);help2.add(helpt2);help2.addSeparator();help2.add(about2);menubar2.add(edit2);menubar2.add(view2);menubar2.add(help2);for(int i = 0;i < COMM.length;i++){comm[i] = new JButton(COMM[i]);panel3.add(comm[i]);comm[i].setForeground(Color.red); }for(int i = 0;i < KON.length;i++){kon[i] = new JButton(KON[i]);panel4.add(kon[i]);kon[i].setForeground(Color.magenta); }kon[4].setForeground(Color.red);kon[9].setForeground(Color.red);kon[14].setForeground(Color.red);kon[19].setForeground(Color.red);kon[0].setForeground(Color.blue);kon[24].setForeground(Color.blue);kon[5].setForeground(Color.blue);kon[10].setForeground(Color.blue);kon[15].setForeground(Color.blue);kon[20].setForeground(Color.blue);for(int i = 0;i < KO.length;i++){ko[i] = new JButton(KO[i]);panel5.add(ko[i]);ko[i].setForeground(Color.red);}ko[0].setForeground(Color.blue);ko[1].setForeground(Color.blue);ko[2].setForeground(Color.blue);ko[6].setForeground(Color.blue);ko[7].setForeground(Color.blue);ko[8].setForeground(Color.blue);ko[12].setForeground(Color.blue);ko[13].setForeground(Color.blue);ko[14].setForeground(Color.blue);ko[18].setForeground(Color.blue);ko[19].setForeground(Color.blue);ko[20].setForeground(Color.blue);//添加监视器for(int i = 0;i < KON.length;i++){kon[i].addActionListener(new ca2Actionlistener()); }for(int i = 0;i < KO.length;i++){ko[i].addActionListener(new ca2Actionlistener());}for(int i = 0;i < COMM.length;i++){comm[i].addActionListener(new ca2Actionlistener()); }checkbox1.addItemListener(new itemListener()); checkbox2.addItemListener(new itemListener()); checkbox3.addItemListener(new itemListener()); checkbox4.addItemListener(new itemListener());JPanel pp1 = new JPanel();pp1.setLayout(new GridLayout(3,1));pp1.add(panel6);JPanel pp2 = new JPanel();pp2.setLayout(new FlowLayout(FlowLayout.LEFT));pp2.add(panel0);pp2.add(new JLabel(" "));pp2.add(panel1);pp1.add(pp2);JPanel pp3 = new JPanel();pp3.setLayout(new FlowLayout(FlowLayout.LEFT));pp3.add(panel2);pp3.add(new JLabel(" "));pp3.add(panel3);pp1.add(pp3);JPanel pp4 = new JPanel();pp4.setLayout(new FlowLayout(FlowLayout.LEFT));JLabel NN = new JLabel(" ");f2.setLayout(new GridLayout(2,1));f2.add(pp1);pp4.add(panel4);pp4.add(NN);pp4.add(panel5);f2.add(pp4);f2.setBackground(Color.LIGHT_GRAY);f2.setSize(655,340);f2.setLocation(200,200);f2.setMenuBar(menubar2);f2.setVisible(false);f2.setResizable(false);f2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);}//科学型初始化结束//****************************************************//标准型监听器public void actionPerformed(ActionEvent e){String label = e.getActionCommand();//获取事件源的标签if(label.equals(COM[0]))//按BackspacehandleBS();else if(label.equals(COM[1]))//按CEresult.setText("0");else if(label.equals(COM[2]))//按ChandleC();else if(label.equals(M[1]))//按MChandleMC();else if(label.equals(M[2]))//按MRhandleMR();else if(label.equals(M[3]))//按MShandleMS();else if(label.equals(M[4]))//按M+handleM();else if("0123456789.".indexOf(label) >= 0)//按数字键或者小数点handleNB(label);else//按运算符handleOR(label);}private void handleBS()//处理Backspace{String text = new String(result.getText());int j = text.length();if(j > 0){text = text.substring(0,j - 1);if(text.length() == 0){result.setText("0");firstDigit = true;operator = "=";}else{result.setText(text);}}}private void handleNB(String key)//处理数字键{if(firstDigit){result.setText(key);}else if((key.equals("."))&&(result.getText().indexOf(".")<0)){result.setText(result.getText() + ".");}else if(!key.equals(".")){result.setText(result.getText() + key);}firstDigit = false;}private void handleC()//处理C{result.setText("0");firstDigit = true;operator = "=";}private void handleOR(String key)//处理运算符{if(operator.equals("/")){if(getNumberFromText() == 0.0){operateValidFlag = false;result.setText("除数不能是零");}elseresultNum /= getNumberFromText();}else if(operator.equals("1/x")){if(resultNum == 0.0){operateValidFlag = false;result.setText("零没有倒数");}elseresultNum = 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("%"))resultNum = 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 ){result.setText(String.valueOf(t1));}else{result.setText(String.valueOf(resultNum));}}//运算符等于用户按的按钮operator = key;firstDigit = true;operateValidFlag = true;}public void handleMC()//处理MC,清除内存{resultNum = 0.0;result.setText("0");m[0].setText(" ");firstDigit = true;operator = "=";}public void handleMR()//处理MR,重新调用存储的数据{if(result.getText() != "" )//有记忆数字{result.setText("" + resultNum);}}public void handleMS()//处理MS,存储显示的数据{resultNum = Double.valueOf(result.getText()).doubleValue();m[0].setText("M");result.setText("0");firstDigit = true;operator = "=";}public void handleM()//处理M+,将显示的数字与已经存储的数据相加要查看新的数字单击MR{resultNum = resultNum + Double.valueOf(result.getText()).doubleValue();}//标准型监听器定义部分结束//****************************************************//科学性监听器定义class itemListener implements ItemListener{public void itemStateChanged(ItemEvent e){Checkbox cb=(Checkbox)e.getItemSelectable(); //获取事件源的resetable(); //使按钮重新可用if(cb.getLabel().equals( "十六进制")){kon[1].setEnabled(false);kon[5].setEnabled(false);kon[6].setEnabled(false);kon[7].setEnabled(false);kon[10].setEnabled(false);kon[11].setEnabled(false);kon[15].setEnabled(false);kon[16].setEnabled(false);kon[20].setEnabled(false);kon[21].setEnabled(false);kon[24].setEnabled(false);kon[1].setForeground(Color.gray);kon[5].setForeground(Color.gray);kon[6].setForeground(Color.gray);kon[7].setForeground(Color.gray);kon[10].setForeground(Color.gray);kon[11].setForeground(Color.gray);kon[15].setForeground(Color.gray);kon[16].setForeground(Color.gray);kon[20].setForeground(Color.gray);kon[21].setForeground(Color.gray);ko[1].setForeground(Color.blue);ko[2].setForeground(Color.blue);ko[24].setForeground(Color.blue);ko[25].setForeground(Color.blue);ko[26].setForeground(Color.blue);ko[27].setForeground(Color.blue);ko[28].setForeground(Color.blue);ko[29].setForeground(Color.blue);ko[0].setForeground(Color.blue);ko[6].setForeground(Color.blue);ko[7].setForeground(Color.blue);ko[8].setForeground(Color.blue);ko[13].setForeground(Color.blue);ko[14].setForeground(Color.blue); }else if(cb.getLabel().equals( "十进制")) {kon[5].setEnabled(false);kon[10].setEnabled(false);kon[15].setEnabled(false);kon[20].setEnabled(false);ko[24].setEnabled(false);ko[25].setEnabled(false);ko[26].setEnabled(false);ko[27].setEnabled(false);ko[28].setEnabled(false);ko[29].setEnabled(false);kon[5].setForeground(Color.gray); kon[10].setForeground(Color.gray); kon[15].setForeground(Color.gray); kon[20].setForeground(Color.gray); ko[24].setForeground(Color.gray);ko[25].setForeground(Color.gray);ko[26].setForeground(Color.gray);ko[27].setForeground(Color.gray);ko[28].setForeground(Color.gray);ko[29].setForeground(Color.gray);ko[1].setForeground(Color.blue);ko[2].setForeground(Color.blue);kon[1].setForeground(Color.magenta);kon[7].setForeground(Color.magenta); kon[11].setForeground(Color.magenta); kon[16].setForeground(Color.magenta); kon[21].setForeground(Color.magenta); kon[24].setForeground(Color.blue);ko[0].setForeground(Color.blue);ko[6].setForeground(Color.blue);ko[7].setForeground(Color.blue);ko[8].setForeground(Color.blue);ko[13].setForeground(Color.blue);ko[14].setForeground(Color.blue);}else if(cb.getLabel().equals( "八进制")) {kon[1].setEnabled(false);kon[5].setEnabled(false);kon[6].setEnabled(false);kon[7].setEnabled(false);kon[10].setEnabled(false);kon[11].setEnabled(false);kon[15].setEnabled(false);kon[16].setEnabled(false);kon[20].setEnabled(false);kon[21].setEnabled(false);kon[24].setEnabled(false);ko[1].setEnabled(false);ko[2].setEnabled(false);ko[24].setEnabled(false);ko[25].setEnabled(false);ko[26].setEnabled(false);ko[27].setEnabled(false);ko[28].setEnabled(false);ko[29].setEnabled(false);kon[1].setForeground(Color.gray);kon[5].setForeground(Color.gray);kon[6].setForeground(Color.gray);kon[7].setForeground(Color.gray);kon[10].setForeground(Color.gray);kon[11].setForeground(Color.gray);kon[15].setForeground(Color.gray);kon[16].setForeground(Color.gray);kon[20].setForeground(Color.gray);kon[24].setForeground(Color.gray);ko[1].setForeground(Color.gray);ko[2].setForeground(Color.gray);ko[24].setForeground(Color.gray);ko[25].setForeground(Color.gray);ko[26].setForeground(Color.gray);ko[27].setForeground(Color.gray);ko[28].setForeground(Color.gray);ko[29].setForeground(Color.gray);ko[0].setForeground(Color.blue);ko[6].setForeground(Color.blue);ko[7].setForeground(Color.blue);ko[8].setForeground(Color.blue);ko[13].setForeground(Color.blue);ko[14].setForeground(Color.blue); }else if(cb.getLabel().equals( "二进制")) {kon[1].setEnabled(false);kon[5].setEnabled(false);kon[6].setEnabled(false);kon[7].setEnabled(false);kon[10].setEnabled(false);kon[11].setEnabled(false);kon[15].setEnabled(false);kon[16].setEnabled(false);kon[20].setEnabled(false);kon[21].setEnabled(false);kon[24].setEnabled(false);ko[1].setEnabled(false);ko[2].setEnabled(false);ko[24].setEnabled(false);ko[25].setEnabled(false);ko[26].setEnabled(false);ko[27].setEnabled(false);ko[28].setEnabled(false);ko[29].setEnabled(false);ko[0].setEnabled(false);ko[6].setEnabled(false);ko[7].setEnabled(false);ko[8].setEnabled(false);ko[13].setEnabled(false);ko[14].setEnabled(false);kon[1].setForeground(Color.gray);kon[5].setForeground(Color.gray);kon[6].setForeground(Color.gray);kon[7].setForeground(Color.gray);kon[10].setForeground(Color.gray);kon[11].setForeground(Color.gray);kon[15].setForeground(Color.gray);kon[16].setForeground(Color.gray);kon[20].setForeground(Color.gray);kon[21].setForeground(Color.gray);kon[24].setForeground(Color.gray);ko[1].setForeground(Color.gray);ko[2].setForeground(Color.gray);ko[24].setForeground(Color.gray);ko[25].setForeground(Color.gray);ko[26].setForeground(Color.gray);ko[27].setForeground(Color.gray);ko[28].setForeground(Color.gray);ko[29].setForeground(Color.gray);ko[0].setForeground(Color.gray);ko[6].setForeground(Color.gray);ko[7].setForeground(Color.gray);ko[8].setForeground(Color.gray);ko[13].setForeground(Color.gray);ko[14].setForeground(Color.gray);}}}class ca2Actionlistener implements ActionListener{public void actionPerformed(ActionEvent e){String label2 = e.getActionCommand();//获取事件源的标签if(label2.equals(COMM[0]))//按BackspacehandleBS2();else if(label2.equals(COMM[1]))//按CEresult2.setText("0");else if(label2.equals(COMM[2]))//按ChandleC2();else if(label2.equals(KON[4]))//按MChandleMC2();else if(label2.equals(KON[9]))//按MRhandleMR2();else if(label2.equals(KON[14]))//按MShandleMS2();else if(label2.equals(KON[19]))//按M+handleM2();else if(label2.equals(KON[11]))//按sinhandleSI();else if(label2.equals(KON[12])) //按x^yhandleYT();else if(label2.equals(KON[13])) //按loghandleLO();else if(label2.equals(KON[16])) //按coshandleCO();else if(label2.equals(KON[17])) //按x^3handleTT();else if(label2.equals(KON[22])) //按x^2handlePF();else if(label2.equals(KON[18])) //按n!handleJC();else if(label2.equals(KON[21])) //按tanhandleTA();else if(label2.equals(KON[24]))//按piresult2.setText(""+3.141592653);else if("0123456789.".indexOf(label2) >= 0)//按数字键或者小数点handleNB2(label2);else//按运算符handleOR2(label2);}}//科学性监听器定义结束//****************************************************//科学性计算器用到的函数void resetable() //使按钮重新可用{for(int i=0;i<KON.length;i++)kon[i].setEnabled(true);for(int i=0;i<KO.length;i++)ko[i].setEnabled(true);}private void handleC2()//处理C{result2.setText("0");firstDigit = true;operator2 = "=";}private void handleBS2()//处理Backspace{String text2 = new String(result2.getText());int j2 = text2.length();if(j2>0){text2 = text2.substring(0,j2 - 1);if(text2.length() == 0){result2.setText("0");firstDigit = true;operator2 = "=";}else{result2.setText(text2);}}}public void handleMC2()//处理MC,清除内存{resultNum2 = 0.0;result2.setText("0");jj.setText(" ");firstDigit = true;operator2 = "=";}private void handleNB2(String key)//处理数字键{if(firstDigit){result2.setText(key);}else if((key.equals("."))&&(result2.getText().indexOf(".")<0)){result2.setText(result2.getText() + ".");}else if(!key.equals(".")){result2.setText(result2.getText() + key);}firstDigit = false;}public void handleMR2()//处理MR,重新调用存储的数据{if(result2.getText() != "" )//有记忆数字result2.setText("" + resultNum2);}public void handleMS2()//处理MS,存储显示的数据{resultNum2 = Double.valueOf(result2.getText()).doubleValue();result2.setText("0");jj.setText("M");firstDigit = true;operator2 = "=";}public void handleM2()//处理M+,将显示的数字与已经存储的数据相加要查看新的数字单击MR{resultNum2 = resultNum2 + Double.valueOf(result2.getText()).doubleValue();}public void handleSI()//sin{double i= getNumberFromText2();result2.setText(String.valueOf(Math.sin(i)));}public void handleYT()//Y次方{if(getNumberFromText2() == 0.0||getNumberFromText2() == 1){resultNum2 = getNumberFromText2();}else{for(int i=1;i<=getNumberFromText2();i++){resultNum2 *=resultNum2;}}result2.setText(String.valueOf(resultNum2));}public void handleLO()//对数{double i= getNumberFromText2();resultNum2 =Math.log(i);result2.setText(String.valueOf(resultNum2));}public void handleCO()//cos{double i= getNumberFromText2();resultNum2 =Math.cos(i);result2.setText(String.valueOf(resultNum2));}public void handleTT()//三次方{if(getNumberFromText2() == 0.0||getNumberFromText2() == 1){resultNum2= getNumberFromText2();}else{resultNum2= getNumberFromText2()*getNumberFromText2()*getNumberFromText2();}result2.setText(String.valueOf(resultNum2));}public void handlePF()//平方{if(getNumberFromText2() == 0.0||getNumberFromText2() == 1){resultNum2 = getNumberFromText2();}else{resultNum2 = getNumberFromText2()*getNumberFromText2();}result2.setText(String.valueOf(resultNum2));}public void handleJC()//阶乘{double i = getNumberFromText2();if((i%2==0)||(i%2==1))//判断为整数放进行阶乘操作{int j = (int)i;//强制类型转换int resultNum2=1;for(int k=1;k<=j;k++)resultNum2 *= k;result2.setText(String.valueOf(resultNum2));}else{result2.setText("无法求阶乘");}}public void handleTA()//tan{double i= getNumberFromText2();resultNum2 =Math.tan(i);result2.setText(String.valueOf(resultNum2));}private void handleOR2(String key)//处理运算符{if(operator2.equals("/")){if(getNumberFromText2() == 0.0){operateValidFlag = false;result2.setText("除数不能是零");}elseresultNum2 /= getNumberFromText2();}else if(operator2.equals("1/x")){if(resultNum2 == 0.0){operateValidFlag = false;result2.setText("零没有倒数");}elseresultNum2 = 1 / resultNum2;}else if(operator2.equals("+"))resultNum2 += getNumberFromText2();else if(operator2.equals("-"))resultNum2 -= getNumberFromText2();else if(operator2.equals("*"))resultNum2 *= getNumberFromText2();else if(operator2.equals("sqrt"))resultNum2 = Math.sqrt(resultNum2);/////////else if(operator2.equals("%"))resultNum2 = resultNum2 / 100;else if(operator2.equals("+/-"))resultNum2 = resultNum2 * (-1);else if(operator2.equals("=")){ resultNum2 = getNumberFromText2();}if(operateValidFlag)// 双精度浮点数的运算{long t1;double t2;t1 = (long) resultNum2;t2 = resultNum2 - t1;if(t2 == 0 ){result2.setText(String.valueOf(t1));}else{result2.setText(String.valueOf(resultNum2));}}//运算符等于用户按的按钮operator2 = key;firstDigit = true;operateValidFlag = true;}//**************************************************** private double getNumberFromText2()/*从结果文本框中获取数字*/{double res2 = 0;try{。
课程设计报告(java版的计算器源代码)
程序功能简介:从最基本的加、减、乘、除,到基本数学函数处理,再到数的进制转换处理。
代码如下/*文件名:Calculator.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("退格");button_cancel=new JButton("C");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_plusminus)||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("退格")) //退格键的实现方法{if(str.length()>0)displayField.setText(str.substring(0,str.length()-1));}else if(input.equals("C")) //清零键的实现方法{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("sqrt,exp等键是先输运算符再输数字\n");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){}}运行结果截图:程序功能实现:1.运用两个面板的叠加做出界面。
北邮JAVA第三次作业科学计算器(附源代码)
北邮JAVA第三次作业科学计算器(附源代码)JAVA第三次作业选题:科学计算器一、设计思路(1)布局1.数字键盘有0~9和小数点2.符号键盘有+某÷,幂,开方,lg,ln3.功能按键有清屏(AC)和删除(Del)(2)计算器流程状态转移图设定的标志位和变量有:booleannumflag=fale;//标志:是否输入数字booleanopflag=fale;//标志:是否输入运算操作符Stringt某t=null;//显示到文本框里的字符串Stringnum_t某t=\;//当前操作数的字符串形式Stringop=\;//存放输入的运算操作符num1=0;//第一个操作数num2=0;//第二个操作数privateBigDecimalbig_num1=newBigDecimal(Double.toString(0)); //解决浮点数的精度丢失问题privateBigDecimalbig_num2=newBigDecimal(Double.toString(0));1.关于操作数操作数为输入数字时会改变的数,有num1和num2。
按下运算符和控制字符,会设定当前下在键入的操作数,由opflag控制,fale表示正在操作num1,true表示正在操作num2。
初始状态下的操作数为num1。
按下AC会恢复操作数为初始状态num1。
按Delete、开方、lg、ln不会改变当前的操作数。
其中后三者只对num1有效。
其他的运算符和控制符都会使操作数为num2。
2.计算器的状态框图输入第一个数,比如53numflag=true(num1)opflag=falenum_t某t=”53”op=””t某t=”53”初始状态numflag=faleopflag=falenum_t某t=””op=””t某t=nullnum1,num2=0按下一个运算符,比如+numflag=faleopflag=truenum_t某t=””op=”+”t某t=”num1+”其中按下按=显示结果,恢复初始状态numflag=true(num1)opflag=falenum_t某t=””op=””t某t=”reult”“=”后,结果存输入第二个数,比如66入numflag=true(num2)opflag=truenum_t某t=”66”op=””t某t=”num1+66”num1,继续输入数字会在num1的结果上处理。
用java编写的计算器的代码
cp3.add(jia);
jia.setForeground(new Color(255,0,0));
jia.addActionListener(this);
cp3.add(deng);
deng.setForeground(new Color(255,0,0));
cp3.add(dd);
dd.addActionListener(this);
cp3.add(ee);
ee.addActionListener(this);
cp3.add(ff);
ff.addActionListener(this);
aa.setVisible(false);
bb.setVisible(false);
cc.setVisible(false);
dd.setVisible(false);
ee.setVisible(false);
ff.setVisible(false);
///有了这个按钮就能按了
num0.addKeyListener(new MyListener());
num5.addKeyListener(new MyListener());
num6.addKeyListener(new MyListener());
num7.addKeyListener(new MyListener());
text.setHorizontalAlignment(JTextField.RIGHT);//从右到左
JPanel cp1=new JPanel();
JPanel cp2=new JPanel();
java课程设计 科学计算器
目录1 课设任务及要求 (1)1.1课设任务: (1)1。
2创新要求: (1)1.3设计要求 (1)2 需求分析 (2)2。
1 设计背景 (2)2.2 开发的技术及功能 (2)3 设计思路 (3)4 详细设计 (4)4。
1功能实现: (4)4。
4 程序设计过程 (6)5 系统调试 (6)5.1 运行调试 (6)6 参考文献 (7)附录 (8)1 课设任务及要求1。
1课设任务:⑴、设计的计算器应用程序可以完成加法、减法、乘法、除法以及取余运算(可以进行浮点数和负数的运算);⑵、有求倒数、退格和清零功能。
1.2创新要求:能进行正切、余弦,以及求平方根、指数(包括对e)、自然对数运算.1.3设计要求①设计的计算器应用程序可以完成加法、减法、乘法、除法和取余运算。
且有小数点、正负号、求倒数、退格和清零功能。
②课程设计可选用Eclipse、JBuilder、NetBeans等作为开发平台以提高开发效率,通过资料查阅和学习尽可能熟练掌握其中一种集成开发环境。
③认真按时完成课程设计报告,课程设计报告内容包括:设计任务与要求、需求分析、设计思路、详细设计、运行调试与分析讨论和设计体会与小结六个部分。
2 需求分析2.1 设计背景设计这个计算器主要是参考Windows操作系统中自带的计算器,由于编者水平和时间的限制,不能将计算器设计到科学型及其他更复杂的类型,在设计过程中还参考了一些其他的优秀设计。
但本计算器除了常用的加减乘除(可以进行浮点和负数运算)这些基本运算外,还有求余、求倒、退格、清零,甚至还能进行一些复杂科学的运算,比如余弦(cos)、正切(tan)、指数运算(pow)、自然对数运算(log)、求平方根(sqrt)以及对e的指数运算(exp),并且还能进行连续运算.总体上说来,本计算器设计简单,代码很少,程序很小,但功能却很强大,这是同类计算器所不具备的.2.2 开发的技术及功能本课程设计是要做一个图形界面的计算器,其界面主要是由swing组件中的控件构成。
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源代码
pack();
setVisible(trห้องสมุดไป่ตู้e);
}
public void setup() //搭建次程序的图形应用界面
{
pan1.setLayout(new BorderLayout());
Labelnow.setFont(wordFont1);
Labelnow.setBackground(Color.gray);
pan3.add(Labelnow);
Labeltime.setBackground(Color.gray);
Labeltime.setFont(wordFont1);
System.out.println("即将计算的表达式是:"+QU);
Labelnow.setText("计算程序正在运行");
appendchar( button20.getLabel());
appendchar( countall ( QU ) );
private Button button9=new Button("9");
private Button button10=new Button("0");
private Button button11=new Button("+");
private Button button12=new Button("-");
{
super("我的科学计算器");
setup();
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
功能举例:
源程序如下:
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
public class Calucator extends JFrame {
private JTextField tf;
private JPanel panel1, panel2, panel3, panel4;
private JMenuBar myBar;
private JMenu menu1, menu2, menu3;
private JMenuItem editItem1, editItem2, help1, help2, help3;
private JRadioButtonMenuItem seeItem1, seeItem2;###");, new Dot(), ;
addButton(panel2, "+", new Signs(), ;
addButton(panel2, "tan", new Signs(), ;
addButton(panel2, "%", new Signs(), ;
addButton(panel2, "π", numActionListener, ;
addButton(panel2, "e", numActionListener, ;
addButton(panel2, "′″", new Signs(), ;
addButton(panel2, "=", new Signs(), ;
JButton btns = new JButton("计算器"); createLoweredBevelBorder());
false);rim());
(i));
}else if(str == "Backspace"){
if()) > 0){
if().length() > 1){
().substring(0, ().length() - 1));
ength() > 2){
().substring(0, ().length() - 1));
}else{
("0");
IfResult = true;
}
}
}else if(str == "CE"){
("0");
IfResult = true;
}
}
}
/**
*数字输入的事件监听
*/
class Num implements ActionListener{
public void actionPerformed(ActionEvent e) { if(IfResult){
("");
IfResult = false;
}
if(str=="π")
{
);
}
else if(str=="e")
{
);
}
else{
().trim() + str);
if().equals("0")){
("0");
IfResult = true;
flag = true;
}
}
}
}
/**
*小数点的事件监听
*/
class Dot implements ActionListener{
public void actionPerformed(ActionEvent e) { IfResult = false;
if().trim().indexOf(".") == -1){
() + ".");
}
}
}
/**
*main方法
*/
public static void main(String[] args) { new Calucator().setVisible(true);
}
}。