java计算器源代码有注解

合集下载

计算器JAVA源代码

计算器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计算器程序代码及文档(带异常处理,括号等。注释详细易懂)

java计算器程序代码及文档(带异常处理,括号等。注释详细易懂)

四则运算计算器设计说明书一.设计目标本次计算器的程序设计,通过使用JA V A中的AWT包和Swing包的类库设计图形界面的计算器。

此计算器能够完成加减乘除的四则混合运算。

利用面向对象程序设计的思想,将各个组件的事件响应分别用不同的方式表达出来,并且使用了图形界面中的事件委托机制来处理事件响应。

二.设计流程1. 分析该计算器需要完成的功能。

用户能够完成添加括号和负号的四则混合运算,并且计算器能够自动识别运算符的优先级,根据用户输入的运算表达式,自动计算出相应的结果。

同时还完成了计算器中C按钮清屏功能和Backspace退格键。

2. 考虑异常处理。

(1)当输入的表达式中出现除零的操作,显示框将显示“Infinity(无穷大)”。

(2)当输入的表达式错误时,将弹出提示框显示“表达式错误请重新输入”(3)当计算器的显示文本框里为没有输入内容时直接点击等号按钮,将弹出提示框显示“对不起,您没有任何输入,请重新输入:”。

(4)当第一次输入乘号键,除号键,右括号,小数点,求余键,等号键,ce 键,Backspace键时提示错误。

4. 考虑数据的处理目标计算表达式通过点击计算器界面上的按钮进行输入,当按下等号之后,计算器通过调用JA V A中script这个包中的相关类和方法来实现数据的处理。

5. 编码实现计算器的功能。

(1)新建相关的文件。

(2)引入JA V A中相关的包。

(3)新建类Jsq,并继承了类Frame,而且实现了接口ActionListener(4)定义相关的变量,创建相关组件,并对组件的属性进行设置。

(5)对所创建的组件进行布局,完成界面的实现。

(6)为各个组件添加事件监听器。

(7)重写事件接口ActionListener的方法public void actionPerformed(ActionEvent e)。

(8)为各个组件编写事件代码,完成每个按钮的不同功能。

三.测试过程的截图1. 程序初始运行界面2运算测试3.混合运算测试:异常处理测试:1.输入错误的表达式2、除数为0时:四.设计结果此计算器以完成设计,所有功能都以实现,并达到了预想的设计目标。

JAVA简易计算器程序源代码

JAVA简易计算器程序源代码

JAVA简易计算器程序源代码package myText;import java.awt.*;import javax.swing.*;import java.awt.event.*;import javax.swing.border.*;public class Calculator extends JFrame implements ActionListener{ private JPanel Panel1=new JPanel();private JPanel Panel2=new JPanel();private JTextField tfResult=new JTextField(25);private JLabel label=new JLabel("计算结果:");private String recentOperation=null;private String recentNum=null;private boolean isNew=true;public void addButton(Container c,String s){JButton b=new JButton(s);b.setFont(new java.awt.Font("SansSerif",0,12));b.setForeground(Color.red);b.setBorder(BorderFactory.createRaisedBevelBorder());c.add(b);b.addActionListener(this);}//end public void addButton(Container c,String s)public void actionPerformed(ActionEvent e){String s=e.getActionCommand();if(s.charAt(0)>='0'&&s.charAt(0)<='9'){if(!isNew){tfResult.setText(tfResult.getText()+s);}//end if(!isNew)else{tfResult.setText(s);}//end elseisNew=false;}//end if(s.charAt(0)>='0'&&s.charAt(0)<='9') else if(s.equals(".")){if(tfResult.getText().indexOf(".")!=-1)return;if(!isNew&&tfResult.getText()!=""){tfResult.setText(tfResult.getText()+".");}//end ifelse{tfResult.setText("0.");}//end elseisNew=false;}//end if(s.equals("."))else if(s.equals("=")){equalaction(e);}//end if(s.equals("="))else{if((tfResult.getText()).equals("")){return;}//endif((tfResult.getText()).equals(""))if(recentOperation!=null){equalaction(e);}//end if(recentOperation!=null) recentOperation=s;recentNum=tfResult.getText();isNew=true;}//end else}//end public void actionPerformed(ActionEvent e) void equalaction(ActionEvent e){if(recentOperation==null||recentNum==null||tfResult.getTex t().equals("")){ return;}//end if()double last=0,now=0;try{last=Double.parseDouble(recentNum);now=Double.parseDouble(tfResult.getText());}//end trycatch(NumberFormatException ne){recentOperation=null;recentNum=null;tfResult.setText("数据输入不合法");System.out.println("数据输入不合法");isNew=true;return;}//end catch(NumberFormatException ne)if(recentOperation.equals("+")){last+=now;}//end if(recentOperation.equals("+"))if(recentOperation.equals("-")){last-=now;}//endif(recentOperation.equals("-"))if(recentOperation.equals("*")){last*=now;}//endif(recentOperation.equals("*"))if(recentOperation.equals("/")){last/=now;}//endif(recentOperation.equals("/"))tfResult.setText(""+last);recentNum=tfResult.getText();recentOperation=null;isNew=true;}//end void equalaction(ActionEvent e)public Calculator(){tfResult.setBorder(BorderFactory.createLoweredBevelBorder ());tfResult.setEditable(false);tfResult.setText("0");tfResult.setHorizontalAlignment(SwingConstants.RIGHT);////本java源代码由839682048整理修改//////Panel1.add(label,FlowLayout.LEFT);Panel1.add(tfResult);////本java源代码由839682048整理修改///Panel2.setLayout(new GridLayout(4,4,2,2));String buttons="789/456*123-0.=+";for(int i=0;i<buttons.length();i++){< p="">addButton(Panel2,buttons.substring(i,i+1));}//end for()//本java源代码由839682048整理修改///this.getContentPane().add(Panel1,"North");this.getContentPane().add(Panel2,"Center");this.setResizable(false);this.setTitle("计算器");this.addWindowListener(newjava.awt.event.WindowAdapter(){public void windowClosing(WindowEvent e){System.exit(0);}});}//end public Calculator1()public static void main(String[]args){Calculator mf=new Calculator();mf.setBounds(200,200,400,400);mf.show();}//end main()}//end public class Calculator1extends JFrame implements ActionListener</buttons.length();i++){<>。

计算器的Java源代码

计算器的Java源代码
button_7.setBorder(BorderFactory.createRaisedBevelBorder());
button_7.setText("7");
button_8.setFont(new Font("SansSerif",0,12));
button_8.setForeground(Color.blue);
button_4.setBorder(BorderFactory.createRaisedBevelBorder());
button_4.setText("4");
button_5.setFont(new Font("SansSerif",0,12));
button_5.setForeground(Color.blue);
//保存最近一次运算符
String recentOperation=null;
//保存最近一次的运算数据
String recentNum=null;
//描述当前输入状态,是重新输入还是接在后面,重新输入时为true
boolean isNew=true;
public Calculator(){
button_4.addActionListener(this);
button_5.addActionListener(this);
button_6.addActionListener(this);
button_7.addActionListener(this);
button_8.addActionListener(this);
JButton button_CE=new JButton();

Java计算器源代码(已成功运行)汇总

Java计算器源代码(已成功运行)汇总
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编写计算器源代码

java编写计算器源代码

计算器的制作import java.awt.*;import java.awt.event.*;class ComputerExe extends Frame implements ActionListener {Button b1,b2,b3,b4;TextField t1,t2,t3;Label l1,l2;public static void main(String[] args)//程序入口{new ComputerExe();//创建本窗体对象}ComputerExe()//构造方法{super("四则运算");setBounds(100,100,300,200);setVisible(true);b1=new Button("加");b2=new Button("减");b3=new Button("乘");b4=new Button("除");t1=new TextField(15);t2=new TextField(15);t3=new TextField(15);l1=new Label("");l2=new Label("=");l1.setBackground(Color.yellow);l1.setForeground(Color.red);l2.setBackground(Color.yellow);l2.setForeground(Color.red);t3.setEditable(false);setLayout(new FlowLayout());//更改窗体框架的布局add(t1);add(l1);add(t2);add(l2);add(t3);add(b1);add(b2);add(b3);add(b4);setVisible(true);b1.addActionListener(this);b2.addActionListener(this);b3.addActionListener(this);b4.addActionListener(this);}//构造方法结束public void actionPerformed(ActionEvent e) { double n1,n2,n3;if(e.getSource()==b1){try{n1=Double.parseDouble(t1.getText());n2=Double.parseDouble(t2.getText());n3=n1+n2;t3.setText(String.valueOf(n3));l1.setText("+");}catch(NumberFormatException w){t3.setText("操作数应该为数字!");}}if(e.getSource()==b2){try{n1=Double.parseDouble(t1.getText());n2=Double.parseDouble(t2.getText());n3=n1-n2;t3.setText(String.valueOf(n3));l1.setText("-");}catch(NumberFormatException w){t3.setText("操作数应该为数字!");}}if(e.getSource()==b3){try{n1=Double.parseDouble(t1.getText());n2=Double.parseDouble(t2.getText());n3=n1*n2;t3.setText(String.valueOf(n3));l1.setText("*");}catch(NumberFormatException w){t3.setText("操作数应该为数字!");}}if(e.getSource()==b4){try{n1=Double.parseDouble(t1.getText());n2=Double.parseDouble(t2.getText());n3=n1/n2;t3.setText(String.valueOf(n3));l1.setText("/");}catch(NumberFormatException w){t3.setText("操作数应该为数字!");}}}}//类结束。

java简单计算器--代码

JOptionPane.ERROR_MESSAGE);return;}
}
}
if(act.equals("sqrt")){try{float num=(float)Math.sqrt(Float.parseFloat(t.getText()));
t.setText(String.valueOf(num));can=true;return;
JOptionPane.ERROR_MESSAGE);return;}
}
}
public float cacu(float a,char c,float b){
float sum;
switch(c){
case '+':sum=a+b;break;
case '-':sum=a-b;break;
t.setText(String.valueOf(num));can=true;return;
}catch(NumberFormatException e1){JOptionPane.showMessageDialog(null, "输入格式错误!", "警告!",
JOptionPane.ERROR_MESSAGE);return;}
p1.add(backButton);
p1.add(clearButton);
backButton.addActionListener(this);
clearButton.addActionListener(this);
p2.add(t);
p2.add(p1);
p2.setBackground(Color.black);

JAVA编写的计算器源代码

JAVA编写的计算器源代码// Calculator.javaimport javax.swing.*; // 引入swing库import java.awt.*; // 引入awt库import java.awt.event.*; // 引入awt.event库public class Calculator extends JFrame implements ActionListener//定义按钮private JButton zero;private JButton one;private JButton two;private JButton three;private JButton four;private JButton five;private JButton six;private JButton seven;private JButton eight;private JButton nine;private JButton point;private JButton equal; private JButton plus; private JButton minus; private JButton multiply; private JButton divide; private JButton backspace; private JButton ac;private JButton ce;private JButton sqrt; private JButton sqr;private JButton plus_minus; private JButton delete; private JButton sin;private JButton cos;private JButton tan;private JButton log;private JButton nfactorial; private JButton cubic; private JButton coln;private JButton factorial;//定义文本框private JTextField resulttext;// 定义boolean变量boolean clrdisp = true; // 昵称确定是否清除计算器显示boolean isCalculate = false; // 是否可以执行计算// 定义String变量,用于存储操作符String optr;//定义存储第一个操作数double num1;//初始化构造函数public Calculato//设置布局setLayout(new BorderLayout();//创建面板JPanel northPanel = new JPanel(;JPanel centerPanel = new JPanel(;JPanel southPanel = new JPanel(;//设置面板布局northPanel.setLayout(new FlowLayout(); centerPanel.setLayout(new GridLayout(4, 5)); southPanel.setLayout(new FlowLayout();//设置计算器显示resulttext = new JTextField(28); northPanel.add(resulttext);resulttext.setEditable(false);//初始化按钮zero = new JButton("0");one = new JButton("1");two = new JButton("2");three = new JButton("3");four = new JButton("4");five = new JButton("5");six = new JButton("6");seven = new JButton("7");eight = new JButton("8");nine = new JButton("9");point = new JButton(".");equal = new JButton("=");plus = new JButton("+");minus = new JButton("-"); multiply = new JButton("*"); divide = new JButton("/"); backspace = new JButton("<-"); ac = new JButton("AC");ce = new JButton("CE");sqrt = new JButton("sqrt");sqr = new JButton("sqr");plus_minus = new JButton("+/-");。

java计算器程序带详细注释

1.import java.awt.*;2.import java.awt.event.*;3.import javax.swing.*;4.5./**比较完整的计算器6. * @author zxsong0077. */8.public class Calculator extends JFrame {9. private static final long serialVersionUID = 428884538177985224L;10. private JButton[] buttons = new JButton[20];// 按钮11. private JTextField textField = new JTextField("0");// 显示器12. private char symbol;// 存放符号13. private double tempvalues;// 临时数值14. private double values;// 结果15. private boolean isDone = false;// 是否计算完成,并清空显示器16.17. public static void main(String[] args) {// main18. new Calculator();19. }20.21. public Calculator() {// 构造22. this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);// 点按钮关闭23. this.setTitle("计算器");//设置标题24. this.setResizable(false); // 禁止最大化25. this.setSize(240, 200);//设置窗口大小26. this.setLocationRelativeTo(this.getOwner());//设置居中显示27. textField.setBounds(5, 5, this.getWidth() - 15, 25);//设置文本框位置28. JLayeredPane pane = this.getLayeredPane();// 获取默认面板29. pane.add(textField);//添加文本框到面板30. textField.setHorizontalAlignment(JTextField.RIGHT);// 文本框右对齐31. textField.setFont(new Font("宋体", 1, 20));// 设置文本框字体加粗32. textField.addKeyListener(new KeyAdapter() {// 文本框键盘事件33.@Override34. public void keyTyped(KeyEvent e) {35. if (e.getKeyChar() < '0' || e.getKeyChar() > '9'){36. e.setKeyChar((char) 0);// 拦截输入的非数字37. Toolkit.getDefaultToolkit().beep();// 发出提示声音38. }39. }40. });41. JLayeredPane p1 = new JLayeredPane();// 新建面板42. p1.setBounds(5, 35, this.getWidth() - 15, this.getHeight() - 70);// 面板位置43. pane.add(p1);// 添加面板到主面板44. GridLayout grid = new GridLayout(5, 4);// 新建布局45. p1.setLayout(grid);// 添加布局46. grid.setVgap(5);// 设置布局行间距47. grid.setHgap(5);// 设置布局列间距48. String[] arr = { "←", "CE", "C", "+/-", "7", "8", "9", "/", "4","5",49. "6", "*", "1", "2", "3", "-", "0", ".", "=", "+" };50. for (int i = 0; i < buttons.length; i++) {51. buttons[i] = new JButton(arr[i]);// 新建按钮,并添加文字52. p1.add(buttons[i]);// 添加按钮到面板53. buttons[i].addActionListener(new CalculatorListener(i));// 添加事件54. }55. this.setVisible(true);// 设置可见56. }57.58. private class CalculatorListener implements ActionListener {// 按钮事件59. private int index;//按钮数组索引60.61. public CalculatorListener(int index) {62. this.index = index;63. }64.65.@Override66. public void actionPerformed(ActionEvent e) {67. String textShow = textField.getText();68. switch (index) {69. default: {// 数字0-970. if (textShow.equals("0")) {//只有1个071. textField.setText(buttons[index].getText());//就直接覆盖,不追加72. } else {//有多个数字73. if (isDone) {//是否清空?74. textField.setText(buttons[index].getText());//直接覆盖75. isDone = false;76. } else//否则追加到尾部77. textField.setText(textShow + buttons[index].getText());78. }79. break;80. }81. case 17: {// 小数点82. if (isDone) {//是否清空?83. textField.setText("0.");//清空84. isDone = false;85. break;86. }87. if (textShow.indexOf('.') == -1) {//保证只有一个小数点88. textField.setText(textShow + ".");89. } else {//已经有小数点90. Toolkit.getDefaultToolkit().beep();//发出提示声音91. }92. break;93. }95. if (textShow.length() <= 1)//只有一位就不用后退96. textField.setText("0");97. else//后退,去掉尾部的数字98. textField.setText(textShow.substring(0,99. textShow.length() - 1));100. break;101. }102. case 3: {// 正负103. if (textShow.startsWith("-"))104. textField.setText(textShow.replace("-", "")); 105. else if (textShow.startsWith("+"))106. textField.setText(textShow.replace("+", "-")); 107. else108. textField.setText("-" + textShow);109. if (isDone) //如果计算完成110. values= parseDouble(textField.getText());//改结果的符号111. else112. tempvalues = parseDouble(textField.getText());//改临时值符号113. break;114. }115. case 2: {// C全部归零116. textField.setText("0");//清空显示器117. symbol = 0;//清空符号118. values = 0;//清空计算的值119. tempvalues = 0;//清空临时值120. isDone = false;121. break;122. }123. case 1: {// CE归零124. textField.setText("0");//只清空显示器125. break;126. }128. if (!isDone) {129. tempvalues = parseDouble(textField.getText()); 130. isDone = true;131. getValue();//计算并显示132. }133. symbol = '+';134. break;135. }136. case 15: {// 减137. if (!isDone) {//还没计算?138. tempvalues = parseDouble(textField.getText()); 139. isDone = true;140. getValue();//计算并显示141. }142. symbol = '-';143. break;144. }145. case 11: {// 乘146. if (!isDone) {//还没计算?147. tempvalues = parseDouble(textField.getText()); 148. isDone = true;149. getValue();//计算并显示150. }151. symbol = '*';152. break;153. }154. case 7: {// 除155. if (!isDone) {//还没计算?156. tempvalues = parseDouble(textField.getText()); 157. isDone = true;158. getValue();//计算并显示159. }160. symbol = '/';161. break;162. }163. case 18: {// 等于164. if (!isDone) {//还没计算?165. tempvalues = parseDouble(textField.getText()); 166. isDone = true;167. }168. getValue();//计算并显示169. break;170. }171. }172.173. }174. }175.176. private double parseDouble(String str) {//字符串转double,一起try 177. double d = 0;178. try {179. d = Double.parseDouble(str);180. } catch (Exception e) {181. Toolkit.getDefaultToolkit().beep();// 异常,发出提示声音182. }183. return d;184. }185.186. private void getValue() {// 判断符号来计算结果187. if (symbol == '+')//加188. values += tempvalues;189. else if (symbol == '-')//减190. values -= tempvalues;191. else if (symbol == '*')//乘192. values *= tempvalues;193. else if (symbol == '/')//除194. values /= tempvalues;195. else if (symbol == 0)//没有运算符196. values = tempvalues;197. if ((long) values == values)// 去掉小数位为0的,结果显示到文本框198. textField.setText((long) values + "");199. else200. textField.setText(values + "");201. }202.}。

java语言写的计算器源代码附解析

//把代码改成Calc.java编译运行,完整版计算器,最下面是计算器界面import java.awt.*;import java.awt.event.*;public class Calc extends WindowAdapter implements ActionListener, MouseListener{Color cMoveOut=new Color(240 ,240 ,240);Color cMoveIn =new Color( 255,255,55);//状态变量boolean clicked=true;//判断是否单击了小数点boolean clear=true;//判断是否单击了符号位double previous;//记录第一个操作数double next;//记录第二个操作数String fuhao;//记录符号位int first=1;//标记是否开始一次新的运算过程Frame f;Panel p1,p2;TextField tf;Font fnt;Button b1,b2,b3,b4,b5,b6,b7,b8,b9,b0;Button bDiv,bSqrt,bMulti,bMinus,bPercent,bPlus,bReciprocal,bEqual,bDot,bNegative,bBack;Button bPingFang , bDaoShu , bSin, bCos ,bTan;Button bC;GridLayout p2Layout;public void display(){f=new Frame("计算器");f.setSize(280,213);f.setLocation(200,200);f.setBackground(Color.LIGHT_GRAY);f.setResizable(false);p1=new Panel(new FlowLayout());tf=new TextField(35);tf.setText("0.");tf.setEditable(false);p1.add(tf);f.add(p1,BorderLayout.NORTH);p2Layout=new GridLayout(5,5,5,4);p2=new Panel(p2Layout);f.add(p2,BorderLayout.CENTER);fnt=new Font("Serief",Font.BOLD,20);b1=new Button("1");b1.setFont(fnt);b2=new Button("2");b2.setFont(fnt);b3=new Button("3");b3.setFont(fnt);b4=new Button("4");b4.setFont(fnt);b5=new Button("5");b5.setFont(fnt);b6=new Button("6");b6.setFont(fnt);b7=new Button("7");b7.setFont(fnt);b8=new Button("8");b8.setFont(fnt);b7.setFont(fnt);b9=new Button("9");b9.setFont(fnt);b0=new Button("0");b0.setFont(fnt);b9.setFont(fnt);bPingFang=new Button("^2"); bPingFang.setFont(fnt); bDaoShu=new Button("1/X"); bDaoShu.setFont(fnt);bSin=new Button("sin");bSin.setFont(fnt);bCos=new Button("cos"); bCos.setFont(fnt);bTan=new Button("tan"); bTan.setFont(fnt);b1.addActionListener(this);b2.addActionListener(this);b3.addActionListener(this);b4.addActionListener(this);b5.addActionListener(this);b6.addActionListener(this);b7.addActionListener(this);b8.addActionListener(this);b9.addActionListener(this);b0.addActionListener(this); bBack=new Button("Back");//退格bBack.setFont(fnt);bC=new Button("C");//清空bC.setFont(fnt);bDiv=new Button("/");bDiv.setFont(fnt);bSqrt=new Button("sqrt"); bSqrt.setFont(fnt);bMulti=new Button("*"); bMulti.setFont(fnt);bMinus=new Button("-"); bMinus.setFont(fnt);bPercent=new Button("%"); bPercent.setFont(fnt);bPlus=new Button("+"); bPlus.setFont(fnt);bEqual=new Button("="); bEqual.setFont(fnt);bDot=new Button(".");bDot.setFont(fnt);bNegative=new Button("+/-"); bNegative.setFont(fnt); bBack.addActionListener(this);bC.addActionListener(this); bDiv.addActionListener(this); bSqrt.addActionListener(this); bPingFang.addActionListener(this); bPercent.addActionListener(this); bDaoShu.addActionListener(this); bMulti.addActionListener(this); bPlus.addActionListener(this); bMinus.addActionListener(this); bMulti.addActionListener(this); bDiv.addActionListener(this); bSin.addActionListener(this); bCos.addActionListener(this); bTan.addActionListener(this); bEqual.addActionListener(this); bDot.addActionListener(this); bNegative.addActionListener(this); bSqrt.addMouseListener(this); bPingFang.addMouseListener(this); bPercent.addMouseListener(this); bC.addMouseListener(this); bBack.addMouseListener(this);b7.addMouseListener(this);b8.addMouseListener(this);b9.addMouseListener(this); bDiv.addMouseListener(this); bDaoShu.addMouseListener(this); b4.addMouseListener(this);b5.addMouseListener(this);b6.addMouseListener(this); bMulti.addMouseListener(this); bSin.addMouseListener(this);b1.addMouseListener(this);b2.addMouseListener(this);b3.addMouseListener(this); bMinus.addMouseListener(this); bCos.addMouseListener(this);b0.addMouseListener(this); bDot.addMouseListener(this); bEqual.addMouseListener(this); bPlus.addMouseListener(this); bTan.addMouseListener(this);p2.add(bSqrt);p2.add(bPingFang);p2.add(bPercent);p2.add(bC);p2.add(bBack);p2.add(b7);p2.add(b8);p2.add(b9);p2.add(bDiv);p2.add(bDaoShu);p2.add(b4);p2.add(b5);p2.add(b6);p2.add(bMulti);p2.add(bSin);p2.add(b1);p2.add(b2);p2.add(b3);p2.add(bMinus);p2.add(bCos);p2.add(b0);p2.add(bDot);p2.add(bEqual);p2.add(bPlus);p2.add(bTan);f.setV isible(true);f.addWindowListener(this);}public void actionPerformed(ActionEvent e) {if (first ==1)tf.setText("");first=0;Object temp=e.getSource();//退格if (temp== bBack){String s=tf.getText();tf.setText("");for (int i=0;i<s.length()-1;i++){char a=s.charAt(i);tf.setText(tf.getText()+a);}}//清零if (temp==bC){tf.setText("0.");clear=true;first=1;}if (temp==b0){//判断是否单击了符号位if (clear==false)tf.setText("");tf.setText(tf.getText()+"0");}if (temp==b1){if (clear==false)tf.setText("");tf.setText(tf.getText()+"1");clear=true;}if (temp==b2){if (clear==false)tf.setText("");tf.setText(tf.getText()+"2");clear=true;}if (temp==b3){if (clear==false)tf.setText("");tf.setText(tf.getText()+"3");clear=true;}if (temp==b4){if (clear==false)tf.setText("");tf.setText(tf.getText()+"4");clear=true;}if (temp==b5){if (clear==false)tf.setText("");tf.setText(tf.getText()+"5");clear=true;}if (temp==b6){if (clear==false)tf.setText("");tf.setText(tf.getText()+"6");clear=true;}if (temp==b7){if (clear==false)tf.setText("");tf.setText(tf.getText()+"7");clear=true;}if (temp==b8){if (clear==false)tf.setText("");tf.setText(tf.getText()+"8");clear=true;}if (temp==b9){if (clear==false)tf.setText("");tf.setText(tf.getText()+"9");clear=true;}//判断是否含有小数点if (temp == bDot){clicked=true;for (int i=0;i<tf.getText().length();i++)if ('.'==tf.getText().charAt(i)){clicked = false;break;}if (clicked == true){tf.setText(tf.getText()+".");clear=true;}}//bSqrtif(temp == bSqrt){tf.setText( Math.sqrt( Double.parseDouble(tf.getText())) + "" );clear=false;}//bPingFangif(temp == bPingFang ){tf.setText( Math.pow( Double.parseDouble(tf.getText() ), 2 ) + "" );clear=false;}//倒数if(temp == bDaoShu){tf.setText( 1 / Double.parseDouble(tf.getText()) + "" );clear =false;}//Sinif(temp == bSin){tf.setText( Math.sin( Math.toRadians( Double.parseDouble( tf.getText() ) ) ) + "" );clear =false;}//Cosif(temp == bCos){tf.setText( Math.cos( Math.toRadians( Double.parseDouble( tf.getText() ) ) ) + "" );clear =false;}//tanif(temp == bTan){tf.setText( Math.tan( Math.toRadians( Double.parseDouble( tf.getText() ) ) ) + "");clear =false;}//加法运算if (temp==bPlus){previous=Double.parseDouble(tf.getText());fuhao="+";clear=false;//System.out.print("+");}//减法运算if (temp == bMinus){previous=Double.parseDouble(tf.getText());fuhao="-";clear=false;}//乘法运算if (temp == bMulti){previous=Double.parseDouble(tf.getText());fuhao="*";clear=false;}//除法运算bDivif (temp == bDiv){previous=Double.parseDouble(tf.getText());fuhao="/";clear=false;}//求余数if(temp == bPercent){previous=Double.parseDouble( tf.getText());fuhao="%";clear=false;}//等于if (temp==bEqual){try{next = Double.parseDouble(tf.getText());tf.setText("");if (fuhao =="+")tf.setText(previous + next +"");if(fuhao == "-")tf.setText(previous - next +"");if(fuhao == "*")tf.setText(previous * next +"");if(fuhao == "/")tf.setText(previous / next +"");if(fuhao == "%")tf.setText(previous % next +"");clear=false;}catch(Exception ex){tf.setText("请检查输入的数据:" + ex.getMessage()) ;clear=false;}}}public void mouseEntered(MouseEvent e){Object temp= e.getSource();if(temp==bPingFang){//System.out.println( bBack.getBackground() );bPingFang.setBackground(cMoveIn);}if(temp==bSqrt){bSqrt.setBackground(cMoveIn);}if(temp==bPercent){bPercent.setBackground(cMoveIn);}if(temp==bC){bC.setBackground(cMoveIn);}if(temp==bBack){bBack.setBackground(cMoveIn);}if(temp==b7){b7.setBackground(cMoveIn);}if(temp==b8){b8.setBackground(cMoveIn);}if(temp==b9){b9.setBackground(cMoveIn);}if(temp==bDiv){bDiv.setBackground(cMoveIn);}if(temp==bDaoShu){bDaoShu.setBackground(cMoveIn); }if(temp==b4){b4.setBackground(cMoveIn);}if(temp==b5){b5.setBackground(cMoveIn);}if(temp==b6){b6.setBackground(cMoveIn);}if(temp==bMulti){bMulti.setBackground(cMoveIn); }if(temp==bSin){bSin.setBackground(cMoveIn);}if(temp==b1){b1.setBackground(cMoveIn);}if(temp==b2){b2.setBackground(cMoveIn);}if(temp==b3){b3.setBackground(cMoveIn);}if(temp==bMinus){bMinus.setBackground(cMoveIn); }if(temp==bCos){bCos.setBackground(cMoveIn);}if(temp==b0){b0.setBackground(cMoveIn);}if(temp==bDot){bDot.setBackground(cMoveIn);}if(temp==bEqual){bEqual.setBackground(cMoveIn);}if(temp==bPlus){bPlus.setBackground(cMoveIn);}if(temp==bTan){bTan.setBackground(cMoveIn);}}public void mouseExited(MouseEvent e) {Object temp= e.getSource();if(temp==bPingFang){//System.out.println( bBack.getBackground() );bPingFang.setBackground(cMoveOut);}if(temp==bSqrt){bSqrt.setBackground(cMoveOut);}if(temp==bPercent){bPercent.setBackground(cMoveOut);}if(temp==bC){bC.setBackground(cMoveOut);}if(temp==bBack){bBack.setBackground(cMoveOut);}if(temp==b7){b7.setBackground(cMoveOut);}if(temp==b8){b8.setBackground(cMoveOut);}if(temp==b9){b9.setBackground(cMoveOut);}if(temp==bDiv){bDiv.setBackground(cMoveOut);}if(temp==bDaoShu){bDaoShu.setBackground(cMoveOut); }if(temp==b4){b4.setBackground(cMoveOut);}if(temp==b5){b5.setBackground(cMoveOut);}if(temp==b6){b6.setBackground(cMoveOut);}if(temp==bMulti){bMulti.setBackground(cMoveOut); }if(temp==bSin){bSin.setBackground(cMoveOut);}if(temp==b1){b1.setBackground(cMoveOut);}if(temp==b2){b2.setBackground(cMoveOut);}if(temp==b3){b3.setBackground(cMoveOut);}if(temp==bMinus){bMinus.setBackground(cMoveOut); }if(temp==bCos){bCos.setBackground(cMoveOut);}if(temp==b0){b0.setBackground(cMoveOut);}if(temp==bDot){bDot.setBackground(cMoveOut);}if(temp==bEqual){bEqual.setBackground(cMoveOut);}if(temp==bPlus){bPlus.setBackground(cMoveOut);}if(temp==bTan){bTan.setBackground(cMoveOut);}}public static void main(String args[]){Calc frame=new Calc();frame.display();}public void windowClosing(WindowEvent e){System.exit(0);}public void mouseClicked(MouseEvent arg0) {}public void mousePressed(MouseEvent arg0) {}public void mouseReleased(MouseEvent arg0) { }}。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
java 计算器源代码-有注解
import java.awt.*; import java.awt.event.*;
import javax.swing.*; public class Calculotor extends Frame { //声明三个面板的布局 GridLayout gl1,gl2,gl3; Panel p0,p1,p2,p3; JTextField tf1; TextField tf2; Button b0,b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,b12,b13,b14,b15,b16,b17,b 18,b19,b20,b21,b22,b23,b24,b25,b26; StringBuffer str;//显示屏所显示的字符串 double x,y;//x 和 y 都是运算数 int z;//Z 表 示 单 击 了 那 一 个 运 算 符 .0 表 示 &quot;+&quot;,1 表 示 &quot;-&quot;,2 表示&quot;*&quot;,3 表示&quot;/&quot;
//添加面板 p3 中的组件并设置其在框架中的位置和大小 p3.setLayout(gl3);//设置 p3 的布局 p3.add(b7); p3.add(b8); p3.add(b9); p3.add(b10); p3.add(b11); p3.add(b12); p3.add(b13); p3.add(b14); p3.add(b15); p3.add(b16); p3.add(b17); p3.add(b18); p3.add(b19); p3.add(b20); p3.add(b21); p3.add(b22); p3.add(b23); p3.add(b24); p3.add(b25); p3.add(b26);
tf1.setText(&quot;&quot;+(-x)); } else if(e2.getSource()==b25)//单击加号按钮获得 x 的值和 z 的值并清空 y 的值 { x=Double.parseDouble(tf1.getText().trim()); str.setLength(0);//清空缓冲区以便接收新的另一个运算数 y=0d; z=0; } else if(e2.getSource()==b20)//单击减号按钮获得 x 的值和 z 的值并清空 y 的值 { x=Double.parseDouble(tf1.getText().trim()); str.setLength(0); y=0d; z=1; } else if(e2.getSource()==b15)//单击乘号按钮获得 x 的值和 z 的值并清
b2=new Button(&quot;C&quot;); b2.setForeground(Color.red); b2.addActionListener(new Bt()); b3=new Button(&quot;MC&quot;); b3.setForeground(Color.red); b3.addActionListener(new Bt()); b4=new Button(&quot;MR&quot;); b4.setForeground(Color.red); b4.addActionListener(new Bt()); b5=new Button(&quot;MS&quot;); b5.setForeground(Color.red); b5.addActionListener(new Bt()); b6=new Button(&quot;M+&quot;); b6.setForeground(Color.red); b6.addActionListener(new Bt()); b7=new Button(&quot;7&quot;); b7.setForeground(Color.blue); b7.addActionListener(new Bt()); b8=new Button(&quot;8&quot;); b8.setForeground(Color.blue); b8.addActionListener(new Bt()); b9=new Button(&quot;9&quot;);
}
//构造监听器 class Bt implements ActionListener { public void actionPerformed(ActionEvent e2) { try{
if(e2.getSource()==b1)//选择&quot;CE&quot;清零 { tf1.setText(&quot;0&quot;);//把显示屏清零 str.setLength(0);//清空字符串缓冲区以准备接收新的输入运算数 } else if(e2.getSource()==b2)//选择&quot;C&quot;清零 { tf1.setText(&quot;0&quot;);//把显示屏清零 str.setLength(0); } else if(e2.getSource()==b23)//单击&quot;+/-&quot;选择输入的运算数是 正数还是负数 { x=Double.parseDouble(tf1.getText().trim());
static double m;//记忆的数字 public Calculotor() { gl1=new GridLayout(1,4,10,0);//实例化三个面板的布局 gl2=new GridLayout(4,1,0,15); gl3=new GridLayout(4,5,10,15);
tf1=new JTextField(27);//显示屏 tf1.setHorizontalAlignment(JTextField.RIGHT); tf1.setEnabled(false); tf1.setText(&quot;0&quot;); tf2=new TextField(10);//显示记忆的索引值 tf2.setEditable(false); //实例化所有按钮、设置其前景色并注册监听器 b0=new Button(&quot;Backspace&quot;); b0.setForeground(Color.red); b0.addActionListener(new Bt()); b1=new Button(&quot;CE&quot;); b1.setForeground(Color.red); b1.addActionListener(new Bt());
b16.addActionListener(new Bt()); b17=new Button(&quot;1&quot;); b17.setForeground(Color.blue); b17.addActionListener(new Bt()); b18=new Button(&quot;2&quot;); b18.setForeground(Color.blue); b18.addActionListener(new Bt()); b19=new Button(&quot;3&quot;); b19.setForeground(Color.blue); b19.addActionListener(new Bt()); b20=new Button(&quot;-&quot;); b20.setForeground(Color.red); b20.addActionListener(new Bt()); b21=new Button(&quot;1/X&quot;); b21.setForeground(Color.blue); b21.addActionListener(new Bt()); b22=new Button(&quot;0&quot;); b22.setFortionListener(new Bt()); b23=new Button(&quot;+/-&quot;); b23.setForeground(Color.blue); b23.addActionListener(new Bt()); b24=new Button(&quot;.&quot;); b24.setForeground(Color.blue); b24.addActionListener(new Bt()); b25=new Button(&quot;+&quot;); b25.setForeground(Color.red); b25.addActionListener(new Bt()); b26=new Button(&quot;=&quot;); b26.setForeground(Color.red); b26.addActionListener(new Bt());
//实例化四个面板 p0=new Panel(); p1=new Panel(); p2=new Panel(); p3=new Panel();
//创建一个空字符串缓冲区 str=new StringBuffer();
//添加面板 p0 中的组件和设置其在框架中的位置和大小 p0.add(tf1); p0.setBounds(10,25,300,40); //添加面板 p1 中的组件和设置其在框架中的位置和大小 p1.setLayout(gl1); p1.add(tf2); p1.add(b0); p1.add(b1); p1.add(b2); p1.setBounds(10,65,300,25); //添加面板 p2 中的组件并设置其的框架中的位置和大小 p2.setLayout(gl2); p2.add(b3); p2.add(b4); p2.add(b5); p2.add(b6); p2.setBounds(10,110,40,150);
相关文档
最新文档