WIN7计算器JAVA程序代码
JAVA-复数计算器
JAVA-复数计算器使⽤java组件做⼀个复数计算器⾸先,建三个类:⼀个组件类,⼀个类(将⽂本框与字符封装起来),⼀个复数类。
下⾯是组件类的代码:package b;import java.awt.*;import java.awt.event.*;import javax.swing.*;import javax.swing.event.*;public class JComplex extends JFrame implements ActionListener{//设置组件public JComboBox<String> combox_add,combox_minus;private static String[] add={"+","-"};private static String[] minus={"+","-"};private JButton button_equal;//建⾯板类的对象ComJPanel x1=new ComJPanel();ComJPanel x2=new ComJPanel();ComJPanel x3=new ComJPanel();ComJPanel result=new ComJPanel();public JComplex(){super("复数运算器");this.setLayout(null);this.setSize(400,220);this.setLocationRelativeTo(null);//添加组件this.add(box_add=new JComboBox<String>(JComplex.add));this.add(box_minus=new JComboBox<String>(JComplex.minus));this.add(this.button_equal=new JButton("="));this.add(x1);this.add(x2);this.add(x3);this.add(result);//设置组件的距离和⼤⼩combox_add.setBounds(20, 70, 60, 30);combox_minus.setBounds(20, 110, 60, 30);button_equal.setBounds(20, 150, 60, 30);x1.setBounds(100, 5, 300, 50);x2.setBounds(100, 50, 300, 50);x3.setBounds(100, 100, 300, 50);result.setBounds(100, 150, 300, 50);//设置动作监听combox_add.addActionListener(this);combox_minus.addActionListener(this);button_equal.addActionListener(this);this.setDefaultCloseOperation(EXIT_ON_CLOSE);this.setVisible(true);}public void actionPerformed(ActionEvent e){//获取⽂本框的内容String s1=x1.text_real.getText();String s2=x1.text_i.getText();String s3=x2.text_real.getText();String s4=x2.text_i.getText();String s5=x3.text_real.getText();String s6=x3.text_i.getText();//建复数类的对象Complex c1=new Complex(s1,s2);Complex c2=new Complex(s3,s4);Complex c3=new Complex(s5,s6);//动作响应if(e.getSource().equals(combox_add)){if(combox_add.getSelectedItem().equals("+")) combox_add.setSelectedItem("+");else if(combox_add.getSelectedItem().equals("-")) combox_add.getSelectedItem().equals("-");}if(e.getSource().equals(combox_minus)){if(combox_minus.getSelectedItem().equals("+")) combox_minus.setSelectedItem("+");else if(combox_minus.getSelectedItem().equals("-")) combox_minus.setSelectedItem("-");}if(e.getSource().equals(button_equal)){if(combox_add.getSelectedItem().equals("+")){c1.add(c2);}else if(combox_add.getSelectedItem().equals("-")) {c1.minus(c2);}if(combox_minus.getSelectedItem().equals("+")){c1.add(c3);}else if(combox_minus.getSelectedItem().equals("-")) {c1.minus(c3);}}result.text_real.setText(Double.toString(c1.x)); result.text_i.setText(Double.toString(c1.y));}public static void main(String []args){new JComplex();}}class ComJPanel extends JPanel {private JLabel label_add,label_i;JTextField text_real,text_i;String s1,s2;public ComJPanel(){//⾯板类this.setLayout(null);this.add(this.text_real=new JTextField());this.add(bel_add=new JLabel("+"));this.add(this.text_i=new JTextField());this.add(bel_i=new JLabel("i"));text_real.setBounds(20,0,100,30);text_i.setBounds(150,0,100, 30);label_add.setBounds(130,0,20, 25); label_i.setBounds(260,0,20, 25);}}复数类就是简单的复数类,就不贴代码啦。
计算器Java编程完全代码
计算器Java编程代码1、界面截图1、程序代码import java.awt.*;import java.awt.event.*;import javax.swing.*;public class Counter implements ActionListener {// 改进小数问题private boolean append = false;JButton[] jb = new JButton[20];JTextField jtf = new JTextField(19);String[] st = { "Backs", "CE", "C", "+", " 7 ", " 8 ", " 9", "-"," 4 ", " 5 ", " 6", "*", " 1 ", " 2 ", " 3", "/"," . ", "+/-", " 0", "=", };String num1 = "0";String operator = "+";public Counter() {JFrame jf = new JFrame("计算器");// 界面设置GridLayout gl = new GridLayout(6, 1);jf.setLayout(gl);JPanel jp0 = new JPanel();jp0.add(jtf);jf.add(jp0);JPanel jp1 = new JPanel();for (int i = 0; i < 4; i++) {jb[i] = new JButton(st[i]);jp1.add(jb[i]);}jf.add(jp1);JPanel jp2 = new JPanel();for (int i = 4; i < 8; i++) {jb[i] = new JButton(st[i]);jp2.add(jb[i]);}jf.add(jp2);JPanel jp3 = new JPanel();for (int i = 8; i < 12; i++) {jb[i] = new JButton(st[i]);jp3.add(jb[i]);}jf.add(jp3);JPanel jp4 = new JPanel();for (int i = 12; i < 16; i++) { jb[i] = new JButton(st[i]);jp4.add(jb[i]);}jf.add(jp4);JPanel jp5 = new JPanel();for (int i = 16; i < 20; i++) { jb[i] = new JButton(st[i]);jp5.add(jb[i]);}jf.add(jp5);jtf.setEditable(false);// 文本框不可编辑jf.setResizable(false);// 窗口不可编辑jf.pack();// 自动调整窗口的大小// jf.setSize(240, 220);jf.setLocation(450, 300);jf.setVisible(true);jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);for (int i = 0; i < 20; i++) {// 注册监听jb[i].addActionListener(this);}}public void actionPerformed(ActionEvent ae) {String s = ae.getActionCommand();if (s.trim().matches("^\\d$")) {// 判断是输入的是否是数字if (append) {// 追加数字String ss = jtf.getText().trim();jtf.setText(ss + s.trim());} else {// 替换文本框原来的数字jtf.setText(s.trim());append = true;}} else if ("+-/*".indexOf(s.trim()) != -1) {// 判断按的是否是四则运算符num1 = jtf.getText();// 将第一次输入的数存储起来operator = s.trim();// 将输入的符号存储起来append = false;} else if ("=".equals(s.trim())) {String num2 = jtf.getText();double d1 = Double.parseDouble(num1);double d2 = Double.parseDouble(num2);if ("+".equals(operator)) {// 加法运算d1 = d1 + d2;} else if ("-".equals(operator)) {// 减法运算d1 = d1 - d2;} else if ("*".equals(operator)) {// 乘法运算d1 = d1 * d2;} else if ("/".equals(operator)) {// 除法运算d1 = d1 / d2;}jtf.setText(d1 + "");// 显示结果append = false;} else if (".".equals(s.trim())) {// 判断小数点String temp = jtf.getText();if (temp.indexOf(".") == -1) {jtf.setText(temp + ".");append = true;}} else if ("+/-".equals(s.trim())) {// 判断+/-String temp = jtf.getText();if(temp.startsWith("-")) {// 如果该数是负数则取负号后的数字jtf.setText(temp.substring(1));} else {// 如果是正数则在这个数前加上负号jtf.setText("-" + temp);}} else if ("CE".equals(s.trim()) || "C".equals(s.trim())) {// 判断复位键jtf.setText("0");append = false;} else if ("BackS".equals(s.trim())) {// 判断BackS键(删除)String temp = jtf.getText();if (temp.length() > 0) {jtf.setText(temp.substring(0, temp.length() - 1));}}}public static void main(String[] args) {new Counter();}}。
用java代码写的简易计算器(可以实现基本的加减乘除功能)
⽤java代码写的简易计算器(可以实现基本的加减乘除功能)package A;import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.MouseEvent;import java.awt.event.MouseListener;import javax.swing.*;public class Calcular3 extends JFrame implements ActionListener,MouseListener{private int m1=0,n=0;//private double m2=0;//运算的数private int flag=0;JFrame f;JPanel p1,p2,p3;JTextField t;JButton b1[]=new JButton[18];String b[]= {"1","2","3","4","5","6","7","8","9","0","清空","退格",".","=","+","-","*","/"};public Calcular3(){f=new JFrame("计算器");t=new JTextField(35);p1=new JPanel();p2=new JPanel();p3=new JPanel();f.setBounds(100, 100, 400, 200);f.add(p1,BorderLayout.NORTH);f.add(p2,BorderLayout.CENTER);f.add(p3,BorderLayout.EAST);p2.setLayout(new GridLayout(5,3));p3.setLayout(new GridLayout(4,1));p1.add(t);for(int i=0;i<14;i++) {b1[i]=new JButton(b[i]);p2.add(b1[i]);b1[i].addActionListener(this);}for(int i=14;i<18;i++) {b1[i]=new JButton(b[i]);p3.add(b1[i]);b1[i].addActionListener(this);}/*for(int i=0;i<18;i++) {b1[i].addActionListener(this);}*/f.setVisible(true);}//实现接⼝的⽅法public void mouseClicked(MouseEvent e) {}public void mousePressed(MouseEvent e) {}public void mouseReleased(MouseEvent e) {}public void mouseEntered(MouseEvent e) {}public void mouseExited(MouseEvent e) {}public void actionPerformed(ActionEvent e) {String str="";int i;for(i=0;i<=9;i++) {if(e.getSource()==b1[i]) {if(i==9) {n=n*10;}else {n=n*10+i+1;}str=String.valueOf(n);//整形n转换成字符串strt.setText(str);//显⽰到⽂本框上}}for(i=14;i<18;i++) {//+、-、*、/if(e.getSource()==b1[i]) {//匹配运算符m1=Integer.parseInt(t.getText());if(flag==15) {m2=m1+m2;}else if(flag==16) {m2=m1-m2;}else if(flag==17) {m2=m1*m2;}else if(flag==18) {m2=m1/m2;}else m2=m1;//若⽆连续的运算符运算,保存当前数据到m2 if(i==14) flag=15;else if(i==15) flag=16;else if(i==16) flag=17;else flag=18;str=String.valueOf(b[i]);t.setText(str);//显⽰到⽂本框上n=0;//还原,记录下次数据break;//找到匹配数据退出循环}}if(e.getSource()==b1[13]) {//=m1=Integer.parseInt(t.getText());if(flag==15) {m2=m2+m1;}else if(flag==16) {m2=m2-m1;}else if(flag==17) {m2=m2*m1;}else if(flag==18) {m2=m2/m1;}else m2=m1;str=String.valueOf(m2);t.setText(str);//显⽰到⽂本框上n=0;//还原,记录下次数据flag=0;//flag还原0,表明没有未处理的运算符}if(e.getSource()==b1[10]) {//各变量变为0 清空m1=0;m2=0;flag=0;n=0;t.setText("0");//显⽰到⽂本框上}if(e.getSource()==b1[11]) {//退格m1=(int)(Double.parseDouble(t.getText())/10);n=m1;str=String.valueOf(m1);t.setText(str);}if(e.getSource()==b1[12]) {//⼩数点m1=Integer.parseInt(t.getText());str=String.valueOf(m1+b[12]);t.setText(str);//显⽰到⽂本框上int j=0;for(i=0;i<=9;i++) {if(e.getSource()==b1[i]) {j++;m2=Math.pow(0.1, j)*Integer.parseInt(b[i]);str=String.valueOf(m1+m2);t.setText(str);//显⽰到⽂本框上}}}}//主函数public static void main(String[] args) {new Calcular3();}}。
科学计算器代码
Calculate.java/*这是一个计算类,用于普通运算中的各种运算,如2,8,10,16进制的符合运算,复合运算其原理用后缀表达式来实现*/import java.util.*;import ng.Math;class Calculate {//两个内部类来实现数据的存储,如同数据结构中的栈class operator{ char data[];int top;operator(){data = new char [50];top = -1;}};class operator1{ double data[];int top;operator1(){data = new double [20];top = -1;}};public static double jiecheng(double number)//阶乘运算{int number1 = (int)number;double j=1;for(int i=1;i<=number1;i++)j=j*i;return j;}String trans (char exp[],char postexp[])//后缀表达式的翻译函数{int i=0,j=0;boolean m=true;//m用来监视表达式是不有非法的运算符连着输入operator op = new operator();while(exp[j]!='\0'){ switch (exp[j]){case '(':op.top++;op.data[op.top]=exp[j];j++;m= false;break;case ')':while (op.data[op.top]!='('){ postexp[i++]=op.data[op.top];op.top--;}op.top--;j++;break;case '+':case '-':if(!m)return "+或者-附近出现多个运算符在一起的现象!";while (op.top!=-1 && op.data[op.top]!='('){postexp[i++]=op.data[op.top];op.top--;}op.top++;op.data[op.top]=exp[j];j++;m=false;break;case '*':case '/':if(!m)return "*或/附近出现多个运算符在一起的现象!";while(op.top!=-1 && op.data[op.top]!='('&& op.data[op.top]!='+'&& op.data[op.top]!='-'){postexp[i++]=op.data[op.top];op.top--;}op.top++;op.data[op.top]=exp[j];j++;m = false;break;case '^':if(!m)return "^(冥运算符号)附近出现多个运算符在一起的现象!";case 's':case 'c':case 't':case 'l':case '$':case '`':op.top++;op.data[op.top]=exp[j];j++;m = false;break;case '!':op.top++;op.data[op.top]=exp[j];j++;break;case ' ':break;default:while (exp[j]>='0' && exp[j]<='9'||exp[j]=='.'){postexp[i++]=exp[j];j++;}postexp[i++]='#';m = true;}}while (op.top!=-1){postexp[i++]=op.data[op.top];op.top--;}postexp[i]='\0';if(exp[j-1]=='+'||exp[j-1]=='-'||exp[j-1]=='*'||exp[j-1]=='/'||exp[j-1]=='^') return "运算式后缀出现非正常运算符!";return "ok";}String compvalue (char postexp[],int flag)//后缀表达式运算,flag为进制{String ex = new String(postexp);StringTokenizer analy = new StringTokenizer(ex,"#+-`*/sclt!^$");operator1 st = new operator1();double d,d1,d2,a,b,c;int j=0;st.top=-1;while (postexp[j]!='\0'){switch (postexp[j]){case '+':a=st.data[st.top];st.top--;b=st.data[st.top];c=a+b;st.data[st.top]=c;break;case '-':a=st.data[st.top];st.top--;b=st.data[st.top];c=b-a;st.data[st.top]=c;break;case '*':a=st.data[st.top];st.top--;b=st.data[st.top];c=a*b;st.data[st.top]=c;break;case '/':a=st.data[st.top];st.top--;b=st.data[st.top];st.top--;if (a!=0){ c=b/a;st.top++;st.data[st.top]=c;}else{ return "输入错误,除数不能是零!请重新输入!";}break;case 's':a=st.data[st.top];c=Math.sin(Math.toRadians(a));st.data[st.top]=c;break;case 'c':a=st.data[st.top];c=Math.cos(Math.toRadians(a));st.data[st.top]=c;break;case 't':a=st.data[st.top];if(a%180 == 90||(-a)%180==90)return "tan函数值有误!";c=Math.tan(Math.toRadians(a));st.data[st.top]=c;break;case '!':a=st.data[st.top];c=jiecheng(a);st.data[st.top]=c;break;case 'l':a=st.data[st.top];if(a<=0)return "log的真数不能小于等于0";c=Math.log(a);st.data[st.top]=c;break;case '^':a=st.data[st.top];st.top--;b=st.data[st.top];c=Math.pow(b,a);st.data[st.top]=c;break;case '$':a=st.data[st.top];if(a<0)return "开方数不能小于0!";c=Math.sqrt(a);st.data[st.top]=c;break;case '`':a=st.data[st.top];c=0-a;st.data[st.top]=c;break;default:String str =analy.nextToken();//获取后缀表达式的数据if(flag == 2)d = btod(str);else if(flag == 8)d = otod(str);else if(flag == 10)d=Double.parseDouble(str);elsed = htod(str);while (postexp[j]>='0' && postexp[j]<='9'||postexp[j]=='.'){j++;}st.top++;st.data[st.top]=d;break;}j++;}return (String.valueOf(st.data[st.top]));}String check(char c[])//检查函数,用来检查运算式中的低级错误{int k=0,i=0;if(c[0]=='+'||c[0]=='-'||c[0]=='^'||c[0]=='*'||c[0]=='/')return "表达式开始位置不对";while(c[k]!='\0'){if((c[k]>=39 && c[k]<='9'&&c[k]!=',') ||c[k]=='$'||c[k]=='!'||c[k]==' '||c[k]=='c'||c[k]=='s'||c[k]=='t'||c[k]=='^'||c[k]=='l'||c[k]=='`') {}else{return "输入含有非法的字符,请重新输入正确的数学表达式!";}if(c[k]=='(')i++;else if(c[k]==')')i--;k++ ;}if(i!=0){return "输入错误,没有相匹配的括弧!请重新输入!";}return "ok";}double btod(String str)//二进制到十进制的转换{int k = str.indexOf("."),m=0;double p=0.0;if(k ==-1)k =str.length();for(int i =k-1;i>=0;i--){char c = str.charAt(i);int a =Integer.parseInt(""+c);p=p+(a*Math.pow(2, m));m++;}m=-1;for(int i =k+1;i<str.length();i++){char c = str.charAt(i);int a =Integer.parseInt(""+c);p=p+(a*Math.pow(2, m));m--;}return p;}double otod(String str)//八进制到十进制的转换{int k = str.indexOf("."),m=0;double p=0.0;if(k ==-1)k =str.length();for(int i =k-1;i>=0;i--){char c = str.charAt(i);int a =Integer.parseInt(""+c);p=p+(a*Math.pow(8, m));m++;}m=-1;for(int i =k+1;i<str.length();i++){char c = str.charAt(i);int a =Integer.parseInt(""+c);p=p+(a*Math.pow(8, m));m--;}return p;}double htod(String str)//十六进制到十进制的转换{int k = str.indexOf("."),m=0;double p=0.0;if(k ==-1)k =str.length();for(int i =k-1;i>=0;i--){char c = str.charAt(i);int a =Integer.parseInt(""+c);p=p+(a*Math.pow(16, m));m++;}m=-1;for(int i =k+1;i<str.length();i++){char c = str.charAt(i);int a =Integer.parseInt(""+c);p=p+(a*Math.pow(16, m));m--;}return p;}}Main.java//主类public class Main {public static void main(String[] args) {new WinFrame("计算器");}}MyDialog.javaimport java.awt.event.*;import java.awt.*;//帮助文档的对话框类class MyDialog extends Dialog implements ActionListener //建立对话框类{ static final int YES=1,NO=0;int message=-1; Button yes,no;TextArea area;String help;MyDialog(Frame f,String s,boolean b) //构造方法{ super(f,s,b);yes=new Button("确定"); yes.addActionListener(this);no=new Button("取消"); no.addActionListener(this);setLayout(new FlowLayout());help = "使用帮助:\n";help +="本计算器运算方式采用输入整个运算式后进行运算的方式.\n";help +="但由于作者能力有限,对有些运算符进行了重定义,现列出以下运算符:\n";help +="s代表sin,c代表cos,t代表tan,!代表阶乘,l代表log\n";help +="`代表负号,如果要用键盘输入的时候,请正确输入\n";help +="本计算器有4大主要功能:\n";help +="1.进行符合运算,可以用键盘进行输入,执行结果可以按回车获得\n";help +="2.进行2,8,10,16进制的各种运算以及相互转换,16进制没有实现a,b,c,d,e,f的输入\n";help +="3.进行大整数运算\n4.进行批量运算";area = new TextArea(help,10,50,3);//area.setEnabled(false);area.setForeground(Color.BLUE);area.setFont(new Font("宋体",Font.BOLD,16));add(area);add(yes); add(no);yes.setPreferredSize(new Dimension(100,25));no.setPreferredSize(new Dimension(100,25));setBounds(300,300,500,300);addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e){ message=-1;setVisible(false);}});}public void actionPerformed(ActionEvent e){ if(e.getSource()==yes){ message=YES;setVisible(false);}else if(e.getSource()==no){ message=NO;setVisible(false);}}public int getMessage(){ return message;}}Mypanel.javaimport java.util.*;import java.awt.*;import javax.swing.*;class mypanel extends Panel//派生一个面板,用来实现不同面板的布局{GridLayout grid;JButton btu[];mypanel(String []btuName,int row,int col,Color c){btu = new JButton [btuName.length];grid = new GridLayout(row,col,1,1);setLayout(grid);for(int i=0;i<row;i++)for(int j=0;j<col;j++){if(i*col+j<btuName.length){btu[i*col+j] = new JButton(btuName[i*col+j]);btu[i*col+j].setForeground(c);add(btu[i*col+j]);btu[i*col+j].setPreferredSize(new Dimension(60,25));}elsebreak;}}}WinFrame.javaimport java.util.*;import java.awt.*;import java.awt.event.*;import javax.swing.*;import ng.Math;import java.math.*;class WinFrame extends Frame implements ActionListener,KeyListener,ItemListener {mypanel pane1,pane2,pane3,pane4,pane5;Label label1,label2;short j_flag=10;//进制运算的标示,初始化为十进制String strAsk="",strAnswer="";boolean b_flag = true;boolean p_flag = true;//批处理开关TextArea text1;//大整数输出专用域MenuBar menubar;Menu menu1,menu2,menu3;MenuItem item1,item2;MyDialog dialog;//帮助文档对话框CheckboxMenuItem menuitem1,menuitem2,menuitem3;String a[] = {"1","2","3",//用数组进行按钮的命名和消息内容的获取"4","5","6","7","8","9","0",".","+/-"};String a1[] = {"1","2","3","4","5","6","7","8","9","0",".","`"};String b[] ={"/","C","*","→","+","=","-","CE"};String c[] ={"sin","cos","tan","!","pow","sprt","log","pi"};String c1[] ={"s","c","t","!","^","$","l","p"};String d[] ={"( ",")"};String d1[] ={"(",")"};String e[] = {" A"," B"," C"," D"," E","F"};JTextField ask ,answer;char exp[];char postexp[];Checkbox box1,box2,box3,box4,box5;CheckboxGroup jin;String data = "0";//大整数储存数据TextArea text2,text3;int opear;CardLayout mycard;String answer1 = "";// 进制转换时的十进制答案储存Long answer2 = (long)0;//其他进制答案储存Panel pCenter;//添加一个容器装专用数据域void area()//初始化布局,只是不想在构造方法中的东西太多,看起来不方便{mycard = new CardLayout();pCenter = new Panel();pCenter.setLayout(mycard);setLayout(new FlowLayout());setBounds(60,60,450,290);menu1 = new Menu("查看");menu2 = new Menu("系统");menu3 = new Menu("帮助");menuitem1 = new CheckboxMenuItem("普通",true);menuitem2 = new CheckboxMenuItem("批处理",false);menuitem3 = new CheckboxMenuItem("大整数",false);item1 = new MenuItem("退出");item2 = new MenuItem("帮助");menuitem1.addItemListener(this);menuitem2.addItemListener(this);menuitem3.addItemListener(this);item1.addActionListener(this);item2.addActionListener(this);menubar = new MenuBar();menu1.add(menuitem1);menu1.add(menuitem2);menu1.addSeparator();//分隔符menu1.add(menuitem3);menu2.add(item1);menu3.add(item2);menuitem1.setShortcut(new MenuShortcut(KeyEvent.VK_P));menuitem2.setShortcut(new MenuShortcut(KeyEvent.VK_D)); menuitem3.setShortcut(new MenuShortcut(KeyEvent.VK_B)); item1.setShortcut(new MenuShortcut(KeyEvent.VK_Q)); item2.setShortcut(new MenuShortcut(KeyEvent.VK_F1));menubar.add(menu2);menubar.add(menu1);menubar.add(menu3);setMenuBar(menubar);dialog = new MyDialog(this,"帮助文档",true);pane1 = new mypanel(a,4,3,Color.red);pane3 = new mypanel(c,4,2,Color.black);pane2 = new mypanel(d,1,2,Color.black);pane4 = new mypanel(b,4,2,Color.BLUE);pane5 = new mypanel(e,1,6,Color.red);jin = new CheckboxGroup();box1 = new Checkbox("二进制",false,jin);box2 = new Checkbox("八进制",false,jin);box3 = new Checkbox("十进制",true,jin);box4 = new Checkbox("十六进制",false,jin);box5 = new Checkbox("大整数运算");pane3 = new mypanel(c,4,2,Color.black);for(int i=0;i<8;i++)pane3.btu[i].addActionListener(this);box1.addItemListener(this);box2.addItemListener(this);box3.addItemListener(this);box4.addItemListener(this);box5.addItemListener(this);for(int i=0;i<12;i++)pane1.btu[i].addActionListener(this);for(int i=0;i<2;i++)pane2.btu[i].addActionListener(this);for(int i=0;i<8;i++)pane4.btu[i].addActionListener(this);ask = new JTextField(38);ask.setHorizontalAlignment(JTextField.RIGHT);answer = new JTextField(38);ask.addKeyListener(this);answer.setHorizontalAlignment(JTextField.RIGHT); answer.setEditable(false);add(ask);add(answer);add(box5);add(box1);add(box2);add(box3);add(box4);text1= new TextArea("",6,10,3);text1.setForeground(Color.BLUE);pCenter.add("1",pane3);pCenter.add("2",text1);add(pCenter);add(pane1);add(pane4);add(pane2);add(pane5);label1 = new Label("请按格式输入批处理的数据,按空格输入下一个,回车输出答案。
java计算器程序代码
import java.awt.*;//计算器实例import java.awt.event.*;public class calculator{public static void main(String args[]){MyWindow my=new MyWindow("计算器");}}class MyWindow extends Frame implements ActionListener{ StringBuffer m=new StringBuffer();int p;TextField tex;Buttonb0,b1,b2,b3,b4,b5,b6,b7,b8,b9,jia,jian,cheng,chu,deng,dian,qingling,kaifang;MyWindow(String s){super(s);//StringBuffer s2=new StringBuffer();//String s;tex=new TextField(18);b0=new Button(" 0 ");b1=new Button(" 1 ");b2=new Button(" 2 ");b3=new Button(" 3 ");b4=new Button(" 4 ");b5=new Button(" 5 ");b6=new Button(" 6 ");b7=new Button(" 7 ");b8=new Button(" 8 ");b9=new Button(" 9 ");dian=new Button(" . ");jia=new Button(" + ");jian=new Button(" - ");cheng=new Button(" × ");chu=new Button(" / ");deng=new Button(" = ");qingling=new Button(" 清零 ");kaifang=new Button(" √ ");setLayout(new FlowLayout());add(tex);add(b0);add(b1);add(b2);add(b3);add(b4);add(b5);add(b6);add(b7);add(b8);add(b9);add(dian);add(jia);add(jian);add(cheng);add(chu);add(kaifang);add(qingling);add(deng);b0.addActionListener(this);b1.addActionListener(this);b2.addActionListener(this);b3.addActionListener(this);b4.addActionListener(this);b5.addActionListener(this);b6.addActionListener(this);b7.addActionListener(this);b8.addActionListener(this);b9.addActionListener(this);jia.addActionListener(this);jian.addActionListener(this);cheng.addActionListener(this);chu.addActionListener(this);dian.addActionListener(this);deng.addActionListener(this);qingling.addActionListener(this); kaifang.addActionListener(this);setBounds(200,200,160,280);setResizable(false);//不可改变大小setVisible(true);validate();addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent ee){ System.exit(0);}});}public void actionPerformed(ActionEvent e){if(e.getSource()==b0){m=m.append("0");tex.setText(String.valueOf(m));}if(e.getSource()==b1){m=m.append("1"); tex.setText(String.valueOf(m)); }if(e.getSource()==b2){m=m.append("2"); tex.setText(String.valueOf(m)); }if(e.getSource()==b3){m=m.append("3"); tex.setText(String.valueOf(m)); }if(e.getSource()==b4){m=m.append("4"); tex.setText(String.valueOf(m));}if(e.getSource()==b5){m=m.append("5"); tex.setText(String.valueOf(m)); }if(e.getSource()==b6){m=m.append("6"); tex.setText(String.valueOf(m)); }if(e.getSource()==b7){m=m.append("7"); tex.setText(String.valueOf(m)); }if(e.getSource()==b8){m=m.append("8"); tex.setText(String.valueOf(m)); }if(e.getSource()==b9){m=m.append("9"); tex.setText(String.valueOf(m)); }if(e.getSource()==jia){m=m.append("+"); tex.setText(String.valueOf(m)); }if(e.getSource()==jian){m=m.append("-"); tex.setText(String.valueOf(m)); }if(e.getSource()==cheng){m=m.append("*"); tex.setText(String.valueOf(m)); }if(e.getSource()==chu){m=m.append("/"); tex.setText(String.valueOf(m)); }if(e.getSource()==dian){m=m.append("."); tex.setText(String.valueOf(m)); }String mm=String.valueOf(m);int p1=mm.indexOf("+");int p2=mm.indexOf("-");int p3=mm.indexOf("*");int p4=mm.indexOf("/");if(p1!=-1){p=p1;}else if(p3!=-1){p=p3;}else if(p2!=-1){p=p2;}else if(p4!=-1){p=p4;}if(e.getSource()==deng){String m1=mm.substring(0,p);String m2=mm.substring(p+1);String ch=mm.substring(p,p+1);//System.out.println(m1);//System.out.println(m2);//System.out.println(ch);if(ch.equals("+")){float n1=Float.parseFloat(m1); float n2=Float.parseFloat(m2); float sum=n1+n2;String su=String.valueOf(sum); tex.setText(su);}if(ch.equals("-")){float n1=Float.parseFloat(m1);float n2=Float.parseFloat(m2);float sum=n1-n2;String su=String.valueOf(sum);tex.setText(su);}if(ch.equals("*")){float n1=Float.parseFloat(m1);float n2=Float.parseFloat(m2);float sum=n1*n2;String su=String.valueOf(sum);tex.setText(su);}if(ch.equals("/")){float n1=Float.parseFloat(m1);float n2=Float.parseFloat(m2);float sum=n1/n2;String su=String.valueOf(sum);tex.setText(su);}}if(e.getSource()==qingling){StringBuffer kk=new StringBuffer(); m=kk;tex.setText("0");// System.out.println(mm);}if(e.getSource()==kaifang){String t=tex.getText();float num=Float.parseFloat(t);double nub=Math.sqrt(num);tex.setText(String.valueOf(nub)); }}}。
计算器源代码
今天在一个QQ群上看到一位朋友发了一个编译未通过的Java计算器源代码,遂收藏下来并将其更正。
Mark之,以供日后参考。
程序比较简单,可以说并不是很好的设计,但对于Java中swing及awt的使用,可以作为一个简单有效的例子。
运行起来如下图所示:下面,将此Java程序分享一下(详细描述见注释):/** @(#)JCalculator.java 1.00 12/29/2009** Email: light_warm@*/import java.awt.*;import java.awt.event.*;import javax.swing.*;/*** A simple calculator program.* <p>I saw this program in a QQ group, and help a friend correct it.</p> ** @author Singyuen Yip* @version 1.00 12/29/2009* @see JFrame* @see ActionListener*/public class JCalculator extends JFrame implements ActionListener { /*** Serial Version UID*/private static final long serialVersionUID = -169068472193786457L;/*** This class help close the Window.* @author Singyuen Yip**/private class WindowCloser extends WindowAdapter {public void windowClosing(WindowEvent we) {System.exit(0);}}int i;// Strings for Digit & Operator buttons.private final String[] str= { "7", "8", "9", "/", "4", "5", "6", "*", "1","2", "3", "-", ".", "0", "=", "+" };// Build buttons.JButton[] buttons = new JButton[str.length];// For cancel or reset.JButton reset = new JButton("CE");// Build the text field to show the result.JTextField display = new JTextField("0");/*** Constructor without parameters.*/public JCalculator() {super("Calculator");// Add a panel.JPanel panel1 = new JPanel(new GridLayout(4, 4));// panel1.setLayout(new GridLayout(4,4));for (i = 0; i < str.length; i++) {buttons[i] = new JButton(str[i]);panel1.add(buttons[i]);}JPanel panel2 = new JPanel(new BorderLayout());// panel2.setLayout(new BorderLayout());panel2.add("Center", display);panel2.add("East", reset);// JPanel panel3 = new Panel();getContentPane().setLayout(new BorderLayout());getContentPane().add("North", panel2);getContentPane().add("Center", panel1);// Add action listener for each digit & operator button.for (i = 0; i < str.length; i++)buttons[i].addActionListener(this);// Add listener for "reset" button.reset.addActionListener(this);// Add listener for "display" button.display.addActionListener(this);// The "close" button "X".addWindowListener(new WindowCloser());// Initialize the window size.setSize(800, 800);// Show the window.// show(); Using show() while JDK version is below 1.5.setVisible(true);// Fit the certain size.pack();}public void actionPerformed(ActionEvent e) {Object target = e.getSource();String label = e.getActionCommand();if (target == reset)handleReset();else if ("0123456789.".indexOf(label) > 0)handleNumber(label);elsehandleOperator(label);}// Is the first digit pressed?boolean isFirstDigit = true;/*** Number handling.* @param key the key of the button.*/public void handleNumber(String key) {if (isFirstDigit)display.setText(key);else if ((key.equals(".")) && (display.getText().indexOf(".") < 0))display.setText(display.getText() + ".");else if (!key.equals("."))display.setText(display.getText() + key);isFirstDigit = false;}/*** Reset the calculator.*/public void handleReset() {display.setText("0");isFirstDigit = true;operator = "=";}double number = 0.0;String operator = "=";/*** Handling the operation.* @param key pressed operator's key.*/public void handleOperator(String key) {if (operator.equals("+"))number += Double.valueOf(display.getText());else if (operator.equals("-"))number -= Double.valueOf(display.getText());else if (operator.equals("*"))number *= Double.valueOf(display.getText());else if (operator.equals("/"))number /= Double.valueOf(display.getText());else if (operator.equals("="))number = Double.valueOf(display.getText());display.setText(String.valueOf(number));operator = key;isFirstDigit = true;}public static void main(String[] args) {new JCalculator();}}。
Java实现简易计算器
Java实训作业题目:Java实现简易计算器学院:姓名:学号:班级:20 年月一、实验目的通过课程设计,主要要达到两个目的,一是检验和巩固专业知识、二是提高综合素质和能力。
此次课程设计实训主要是Java语言程序设计的实现。
通过该课程设计,可以将课堂上掌握的理论知识与处理数据的业务相结合,以检验自己掌握知识的宽度、深度及对知识的综合运用能力。
二、实验要求用Java编写一个简单的计算器,使其能够实现最基本的功能,如简单的加、减、乘、除;平方根,倒数,平方等功能。
三、详细内容1.界面设计界面设计使用GUI,其中有用到swing组件的TextField和Button,用到awt中的BorderLayout和GridLayout布局管理方式,其图形界面如图1-1所示:图1-1其中主要代码为:public mainWindow(){this.setTitle("计算器");//用户图形界面标题this.setVisible(true);//用户图形界面可缩小this.setResizable(false);//用户图形界面不可放大this.setSize(350,300);//设置用户图形界面的大小this.setLocation(400,150);//用户图形界面在屏幕中的显示位置JPanel panel1 = new JPanel();//新建一个画板JPanel panel2 = new JPanel();button1 = new JButton("1");...reset = new JButton("CE");Container container = this.getContentPane();container.add(panel2,BorderLayout.NORTH);container.add(panel1);panel1.setLayout(new GridLayout(5,4));//将画板1分为4行5列result.setEnabled(false);result.setFont(new Font("Dialog",Font.BOLD,25));//运算结果的字体大小result.setEditable(false);result.setHorizontalAlignment(SwingConstants.RIGHT);panel1.add(reciprocal);//分别将20个按钮依次添加到画板panel1中,并设置各自的大小reciprocal.setFont(new Font("Dialog",Font.PLAIN,20));...panel1.add(divide);divide.setFont(new Font("Dialog",Font.PLAIN,20));panel2.setLayout(new GridLayout());panel2.add(result);//画板panel2添加运算结果2.四则运算较为简单的实现了简单的加、减、乘、除运算,主要代码如下:ActionListener equal1 = new ActionListener(){ //实现四则运算public void actionPerformed(ActionEvent e){String str = result.getText();b = DatatypeConverter.parseDouble(str);{if(flag == "+")c = a + b;else if(flag == "-")c = a - b;else if(flag == "*")c = a * b;else if(flag == "/" || b != 0)c = a / b;}if(flag != "=")result.setText("" + c);elseresult.setText("零不能做除数!");a = 0;b = 0;c = 0;flag = "";}};3.其他功能另外添加了平方根,倒数,平方等功能,主要代码如下:平方根运算的实现:ActionListener sqrt1= new ActionListener(){public void actionPerformed(ActionEvent e){String str = result.getText();double i = DatatypeConverter.parseDouble(str);i = Math.sqrt(i);result.setText("" + i);}};倒数运算的实现:ActionListener reciprocal1 = new ActionListener(){ public void actionPerformed(ActionEvent e){String str = result.getText();double i = DatatypeConverter.parseDouble(str);i = 1/i;result.setText("" + i);}};平方运算的实现:ActionListener square1 = new ActionListener(){public void actionPerformed(ActionEvent e){String str = result.getText();double i = DatatypeConverter.parseDouble(str);i = i*i;result.setText("" + i);}};4.程序测试经测试发现本计算器基本功能均能实现,可正常运行计算,针对功能实现的代码部分过于简单,可以对其进行改善提高,方便用户使用!5.实训小结通过对计算器窗体的编写,熟悉了java图形用户界面的设计原理和程序结构,熟悉了java中awt和swing的组合。
java计算器源代码(仿win7)
java计算器源代码(仿win7)import java.awt.*;import javax.swing.*;import java.awt.event.*;class Cal extends JFrame implements ActionListener,MouseListener{JMenuBar menubar;JMenu menu_check,menu_edit,menu_help;JMenuItem menuitem_science,menuitem_check,menuitem_exit,menuitem_copy,menuitem_paste,menuitem1_copy,menuitem1_paste,menuitem_chelp,menuitem_about;JCheckBoxMenuItem menuitem_standard;JTextField ta1;int x,result2;double op1,op2,opall;private boolean end=false,flag=false,add=false,sub=false,cheng=false,chu=false,flagop2=false;JButton b_mc,b_mr,b_ms,b_mjia,b_mjian,b_tui,b_ce,b_c,b_jj,b_dui,b_7,b_8,b_9,b_chu,b_baifenhao,b_4,b_5,b_6,b_cheng,b_daoshu,b_1,b_2,b_3,b_jian,b_0,b_dian,b_jia,b_dengyu;JPanel p_all,p_button1,p_button2,p_txt,p1,p2,p3,p4,p5;private String str,resultstr;JPopupMenu popupmenu;Container con=this.getContentPane();Font font=new Font("微软雅黑",Font.PLAIN,12);Color color=new Color(120,220,120);Cal(String s){super(s);setSize(220,315);setResizable(false);setVisible(true);Dimension scr=Toolkit.getDefaultToolkit().getScreenSize();Dimension frm=this.getSize();setLocation((scr.width-frm.width)/2,(scr.height-frm.height)/2);Toolkit tk=Toolkit.getDefaultToolkit();//程序默认图标设置setIconImage(tk.createImage("D:\\sd.jpg"));setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//-----------------------------------------------------------------制作框架结构------------------------- //---------------------------------------菜单栏---------------------------menubar=new JMenuBar();menubar.setPreferredSize(new Dimension(frm.width,19));menu_check=new JMenu("查看(V)");menu_check.setFont(font);menu_check.setForeground(Color.black);menuitem_standard=new JCheckBoxMenuItem("标准型",true);menuitem_standard.setFont(font);menuitem_standard.setForeground(Color.black);menuitem_science=new JMenuItem("科学型");menuitem_science.setFont(font);menuitem_science.setForeground(Color.black);menuitem_check=new JMenuItem("查看分组");menuitem_check.setFont(font);menuitem_check.setForeground(Color.black);menuitem_exit=new JMenuItem("退出");menuitem_exit.setFont(font);menuitem_exit.setForeground(Color.black);menuitem_exit.addActionListener(this);menu_check.add(menuitem_standard);menu_check.add(menuitem_science);menu_check.addSeparator();menu_check.add(menuitem_check);menu_check.addSeparator();menu_check.add(menuitem_exit);menubar.add(menu_check);menu_edit=new JMenu("编辑(E)");menu_edit.setFont(font);menu_edit.setForeground(Color.black);menu_edit.setMnemonic(KeyEvent.VK_E);menuitem_copy=new JMenuItem("复制(C) ");menuitem_copy.setFont(font);menuitem_copy.setForeground(Color.black);menuitem_copy.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C,InputEvent.CTRL_M ASK));menuitem_copy.addActionListener(this);menuitem_paste=new JMenuItem("粘贴(P) ");menuitem_paste.setFont(font);menuitem_paste.setForeground(Color.black);menuitem_paste.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V,InputEvent.CTRL_M ASK));menuitem_paste.addActionListener(this);menu_edit.add(menuitem_copy);menu_edit.add(menuitem_paste);menubar.add(menu_edit);menu_help=new JMenu("帮助(H)");menu_help.setFont(font);menu_help.setForeground(Color.black);menuitem_chelp=new JMenuItem("查看帮助");menuitem_chelp.setFont(font);menuitem_chelp.setForeground(Color.black);menuitem_about=new JMenuItem("关于计算器");menuitem_about.setFont(font);menuitem_about.setForeground(Color.black);menuitem_about.addActionListener(this);menu_help.add(menuitem_chelp);menu_help.addSeparator();menu_help.add(menuitem_about);menubar.add(menu_help);setJMenuBar(menubar);//--------------------------------------文本框----------------------------------ta1=new JTextField("0");ta1.setFont(new Font("微软雅黑",Font.PLAIN,13));ta1.setEditable(false);//ta1.setOpaque(false);ta1.setHorizontalAlignment(JTextField.RIGHT);ta1.setPreferredSize(new Dimension((frm.width-26),45));ta1.addMouseListener(this);p_all=new JPanel();p_all.setPreferredSize(new Dimension((frm.width-6),250));//p_all.setBackground(color);p_all.setLayout(new FlowLayout(FlowLayout.CENTER,0,3));p_txt=new JPanel();p_txt.setPreferredSize(new Dimension((frm.width-6),53));p_txt.setLayout(new FlowLayout(FlowLayout.CENTER,0,7));p_txt.add(ta1);p_all.add(p_txt);con.add(p_all,BorderLayout.CENTER);//-------------------------------------按钮区----------------------------------p_button1=new JPanel();p_button1.setPreferredSize(new Dimension((frm.width-25),131)); p_button1.setLayout(new FlowLayout(FlowLayout.LEFT,0,3));p_all.add(p_button1);p1=new JPanel();p1.setPreferredSize(new Dimension((frm.width-25),127));p1.setLayout(new GridLayout(4,5,5,6));b_mc=new JButton("MC");b_mc.setFont(new Font("微软雅黑",Font.PLAIN,11));b_mc.setMargin(new Insets(0,0,0,0));b_mc.setForeground(Color.blue);b_mc.addActionListener(this);b_mr=new JButton("MR");b_mr.setFont(new Font("微软雅黑",Font.PLAIN,11));b_mr.setMargin(new Insets(0,0,0,0));b_mr.setForeground(Color.blue);b_mr.addActionListener(this);b_ms=new JButton("MS");b_ms.setFont(new Font("微软雅黑",Font.PLAIN,11));b_ms.setMargin(new Insets(0,0,0,0));b_ms.setForeground(Color.blue);b_ms.addActionListener(this);b_mjia=new JButton("M+");b_mjia.setFont(new Font("微软雅黑",Font.PLAIN,11));b_mjia.setMargin(new Insets(0,0,0,0));b_mjia.setForeground(Color.blue);b_mjia.addActionListener(this);b_mjian=new JButton("M-");b_mjian.setFont(new Font("微软雅黑",Font.PLAIN,11)); b_mjian.setMargin(new Insets(0,0,0,0));b_mjian.setForeground(Color.blue);b_mjian.addActionListener(this);b_tui=new JButton("←");b_tui.setFont(new Font("微软雅黑",Font.BOLD,14));b_tui.setMargin(new Insets(0,0,0,0));b_tui.addActionListener(this);b_tui.setForeground(Color.red);b_ce=new JButton("CE");b_ce.setFont(new Font("微软雅黑",Font.PLAIN,11));b_ce.setMargin(new Insets(0,0,0,0));b_ce.setForeground(Color.red);b_ce.addActionListener(this);b_c=new JButton("C");b_c.setFont(new Font("微软雅黑",Font.PLAIN,11));b_c.setMargin(new Insets(0,0,0,0));b_c.setForeground(Color.red);b_c.addActionListener(this);b_jj=new JButton("±");b_jj.setFont(new Font("微软雅黑",Font.PLAIN,14));b_jj.setMargin(new Insets(0,0,0,0));b_jj.setForeground(Color.red);b_jj.addActionListener(this);b_dui=new JButton("√");b_dui.setFont(new Font("微软雅黑",Font.PLAIN,11)); b_dui.setMargin(new Insets(0,0,0,0));b_dui.setForeground(Color.red);b_dui.addActionListener(this);b_7=new JButton("7");b_7.setFont(new Font("微软雅黑",Font.PLAIN,14));b_7.setMargin(new Insets(0,0,0,0));b_7.setForeground(Color.blue);b_7.setMnemonic(KeyEvent.VK_7);b_7.addActionListener(this);b_8=new JButton("8");b_8.setFont(new Font("微软雅黑",Font.PLAIN,14));b_8.setMargin(new Insets(0,0,0,0));b_8.setForeground(Color.blue);b_8.setMnemonic(KeyEvent.VK_8);b_8.addActionListener(this);b_9=new JButton("9");b_9.setMargin(new Insets(0,0,0,0));b_9.setForeground(Color.blue);b_9.setMnemonic(KeyEvent.VK_9);b_9.addActionListener(this);b_chu=new JButton("/");b_chu.setFont(new Font("微软雅黑",Font.PLAIN,14));b_chu.setMargin(new Insets(0,0,0,0));b_chu.setForeground(Color.red);b_chu.addActionListener(this);b_baifenhao=new JButton("%");b_baifenhao.setFont(new Font("微软雅黑",Font.PLAIN,11)); b_baifenhao.setMargin(new Insets(0,0,0,0));b_baifenhao.setForeground(Color.blue);b_baifenhao.addActionListener(this);b_4=new JButton("4");b_4.setFont(new Font("微软雅黑",Font.PLAIN,14));b_4.setMargin(new Insets(0,0,0,0));b_4.setForeground(Color.blue);b_4.setMnemonic(KeyEvent.VK_4);b_4.addActionListener(this);b_5=new JButton("5");b_5.setFont(new Font("微软雅黑",Font.PLAIN,14));b_5.setMargin(new Insets(0,0,0,0));b_5.setForeground(Color.blue);b_5.setMnemonic(KeyEvent.VK_5);b_5.addActionListener(this);b_6=new JButton("6");b_6.setFont(new Font("微软雅黑",Font.PLAIN,14));b_6.setMargin(new Insets(0,0,0,0));b_6.setForeground(Color.blue);b_6.setMnemonic(KeyEvent.VK_6);b_6.addActionListener(this);b_cheng=new JButton("*");b_cheng.setFont(new Font("微软雅黑",Font.PLAIN,14));b_cheng.setMargin(new Insets(0,0,0,0));b_cheng.setForeground(Color.red);b_cheng.addActionListener(this);b_daoshu=new JButton("1/x");b_daoshu.setFont(new Font("微软雅黑",Font.PLAIN,11)); b_daoshu.setMargin(new Insets(0,0,0,0));b_daoshu.setForeground(Color.blue);b_daoshu.addActionListener(this);b_1=new JButton("1");b_1.setMargin(new Insets(0,0,0,0));b_1.setForeground(Color.blue);b_1.setMnemonic(KeyEvent.VK_1);b_1.addActionListener(this);b_2=new JButton("2");b_2.setFont(new Font("微软雅黑",Font.PLAIN,14)); b_2.setMargin(new Insets(0,0,0,0));b_2.setForeground(Color.blue);b_2.setMnemonic(KeyEvent.VK_2);b_2.addActionListener(this);b_3=new JButton("3");b_3.setFont(new Font("微软雅黑",Font.PLAIN,14)); b_3.setMargin(new Insets(0,0,0,0));b_3.setForeground(Color.blue);b_3.setMnemonic(KeyEvent.VK_3);b_3.addActionListener(this);b_jian=new JButton("-");b_jian.setFont(new Font("微软雅黑",Font.PLAIN,14)); b_jian.setMargin(new Insets(0,0,0,0));b_jian.setForeground(Color.red);b_jian.addActionListener(this);b_0=new JButton("0");b_0.setFont(new Font("微软雅黑",Font.PLAIN,14)); b_0.setMargin(new Insets(0,0,0,0));b_0.setPreferredSize(new Dimension(75,27));b_0.setForeground(Color.blue);b_0.setMnemonic(KeyEvent.VK_0);b_0.addActionListener(this);JLabel L1=new JLabel();L1.setPreferredSize(new Dimension(5,3));b_dian=new JButton(".");b_dian.setFont(new Font("微软雅黑",Font.BOLD,14)); b_dian.setMargin(new Insets(0,0,0,0));b_dian.setPreferredSize(new Dimension(35,27));b_dian.setForeground(Color.blue);b_dian.addActionListener(this);JLabel L2=new JLabel();L2.setPreferredSize(new Dimension(5,3));b_jia=new JButton("+");b_jia.setFont(new Font("微软雅黑",Font.BOLD,14)); b_jia.setMargin(new Insets(0,0,0,0));b_jia.setPreferredSize(new Dimension(35,27));b_jia.setForeground(Color.red);b_jia.addActionListener(this);b_dengyu=new JButton("=");b_dengyu.setFont(new Font("微软雅黑",Font.BOLD,22));b_dengyu.setMargin(new Insets(0,0,0,0));b_dengyu.setPreferredSize(new Dimension(35,60));b_dengyu.setForeground(Color.blue);b_dengyu.addActionListener(this);p1.add(b_mc);p1.add(b_mr);p1.add(b_ms);p1.add(b_mjia);p1.add(b_mjian);p1.add(b_tui);p1.add(b_ce);p1.add(b_c);p1.add(b_jj);p1.add(b_dui);p1.add(b_7);p1.add(b_8);p1.add(b_9);p1.add(b_chu);p1.add(b_baifenhao);p1.add(b_4);p1.add(b_5);p1.add(b_6);p1.add(b_cheng);p1.add(b_daoshu);p_button1.add(p1);p_button2=new JPanel();p_button2.setPreferredSize(new Dimension((frm.width-24),65)); p_button2.setLayout(new FlowLayout(FlowLayout.LEFT,0,0));p_all.add(p_button2);p2=new JPanel();p2.setPreferredSize(new Dimension(156,65));p2.setLayout(new FlowLayout(FlowLayout.LEFT,0,1));p3=new JPanel();p3.setPreferredSize(new Dimension(39,62));p3.setLayout(new FlowLayout(FlowLayout.LEFT,4,0));p_button2.add(p2);p_button2.add(p3);p4=new JPanel();p4.setPreferredSize(new Dimension(156,27));p4.setLayout(new GridLayout(1,4,5,5));p5=new JPanel();p5.setPreferredSize(new Dimension(156,39));p5.setLayout(new FlowLayout(FlowLayout.LEFT,0,5));p2.add(p4);p2.add(p5);p4.add(b_1);p4.add(b_2);p4.add(b_3);p4.add(b_jian);p5.add(b_0);p5.add(L1);p5.add(b_dian);p5.add(L2);p5.add(b_jia);p3.add(b_dengyu);//---------------------------------------快捷菜单对象-------------------------popupmenu=new JPopupMenu(); //快捷菜单对象menuitem1_copy=new JMenuItem("复制");menuitem1_copy.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C,InputEvent.CTRL_ MASK));menuitem1_copy.addActionListener(this); //监视鼠标右击菜单”复制“popupmenu.add(menuitem1_copy);menuitem1_paste=new JMenuItem("粘贴");menuitem1_paste.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V,InputEvent.CTRL_MASK));menuitem1_paste.addActionListener(this); //监视鼠标右击菜单”粘贴“popupmenu.add(menuitem1_paste);ta1.add(popupmenu);con.validate();validate();}//---------------------------------------功能区------------------------------------public void actionPerformed(ActionEvent e){if(e.getSource()==menuitem_about){JOptionPane.showMessageDialog(null,"这是一个模仿win7的计算器!欢迎改进,\n创作者:钟作明","仿win7计算器",RMATION_MESSAGE);}if(e.getSource()==menuitem1_copy){ta1.selectAll();ta1.copy();}else if(e.getSource()==menuitem1_paste){ta1.setEditable(true);ta1.setText("");ta1.paste();ta1.setEditable(false);}else if(e.getSource()==menuitem_copy){ta1.selectAll();ta1.copy();}else if(e.getSource()==menuitem_paste){ta1.setEditable(true);ta1.setText("");ta1.paste();ta1.setEditable(false);}else if(e.getSource()==menuitem_exit){System.exit(0);}else if(e.getSource()==b_ce){ta1.setEditable(true);ta1.setText("0");ta1.setEditable(false);}else if(e.getSource()==b_c){ta1.setEditable(true);ta1.setText("0");ta1.setEditable(false);}else if(e.getSource()==b_tui){String str=ta1.getText();StringBuffer s=new StringBuffer(str);int L=s.length();try{if(L!=1){s=s.deleteCharAt(L-1);}else{s=new StringBuffer("0");}}catch(Exception e1){}ta1.setText(String.valueOf(s));}//---------------------------------------------数字键----------------------------- if(e.getSource()==b_1){addString(1);}else if(e.getSource()==b_2){addString(2);}else if(e.getSource()==b_3){addString(3);}else if(e.getSource()==b_4){addString(4);}else if(e.getSource()==b_5){addString(5);}else if(e.getSource()==b_6){addString(6);}else if(e.getSource()==b_7){addString(7);}else if(e.getSource()==b_8){addString(8);}else if(e.getSource()==b_9){addString(9);}else if(e.getSource()==b_0){addString(0);}else if(e.getSource()==b_dian){StringBuffer s1=new StringBuffer(ta1.getText());StringBuffer dian=new StringBuffer(".");if(String.valueOf(s1).indexOf(".")==-1){s1.append(dian);}ta1.setText(String.valueOf(s1));}else if(e.getSource()==b_jj){String txt=ta1.getText();int result=Integer.parseInt(txt);if(txt.indexOf("-")==-1&&txt.length()>0){if(result!=0){txt="-"+txt;}}else{StringBuffer txt1=new StringBuffer(txt);txt1=txt1.deleteCharAt(0);txt=String.valueOf(txt1);}ta1.setText(txt);}else if(e.getSource()==b_dui){str=ta1.getText();Double d=Double.parseDouble(str);if(d>=0){double d1=Math.sqrt(d);String s = String.valueOf(d1);if(s.endsWith(".0")==true){int z=(int)d1;str=String.valueOf(z);}else{str=String.valueOf(d1);}ta1.setText(str);}else{JOptionPane.showMessageDialog(null,"根号底数不能为负数","提醒", RMATION_MESSAGE);}end=true;}else if(e.getSource()==b_baifenhao){str=ta1.getText();Double d=Double.parseDouble(str);ta1.setText(""+d/100);end=true;}else if(e.getSource()==b_daoshu){str=ta1.getText();Double d=Double.parseDouble(str);if(d!=0){ta1.setText(""+1/d);}else{JOptionPane.showMessageDialog(null,"除数不能为零","提醒", RMATION_MESSAGE);}end=true;}else if(e.getSource()==b_jia){str = ta1.getText();op1 = Double.parseDouble(str);end=true;x=0;opall=op1;flagop2=false;}else if(e.getSource()==b_jian){str = ta1.getText();op1 = Double.parseDouble(str);end=true;x=1;opall=op1;flagop2=false;}else if(e.getSource()==b_cheng){str = ta1.getText();op1 = Double.parseDouble(str);end=true;x=2;opall=op1;flagop2=false;}else if(e.getSource()==b_chu){str = ta1.getText();op1 = Double.parseDouble(str);end=true;x=3;opall=op1;flagop2=false;}else if(e.getSource()==b_dengyu){str = ta1.getText();if(flagop2==false){op2 = Double.parseDouble(str);flagop2=true;}switch(x){case 0 :opall=opall+op2;String s=String.valueOf(opall);if(s.endsWith(".0")==true){result2=(int)opall;resultstr=String.valueOf(result2);}else{resultstr=String.valueOf(opall);}ta1.setText(resultstr);break;case 1 :opall=opall-op2;s=String.valueOf(opall);if(s.endsWith(".0")==true){result2=(int)opall;resultstr=String.valueOf(result2);}else{resultstr=String.valueOf(opall);}ta1.setText(resultstr);break;case 2 :opall=opall*op2;s=String.valueOf(opall);if(s.endsWith(".0")==true){result2=(int)opall;resultstr=String.valueOf(result2);}else{resultstr=String.valueOf(opall);}ta1.setText(resultstr);break;case 3 :opall=opall/op2;s=String.valueOf(opall);if(s.endsWith(".0")==true){result2=(int)opall;resultstr=String.valueOf(result2);}else{resultstr=String.valueOf(opall);}ta1.setText(resultstr);break;}end=true;}}public void addString(int num){String s=null;s=String.valueOf(num);//如果end==true;,那么屏幕清空if(end==true){ta1.setText("0");end=false;}if((ta1.getText()).equals("0")){ta1.setText(s);}else{if(ta1.getText().length()<21){str=ta1.getText()+s;ta1.setText(str);}}}public void mouseClicked(MouseEvent mec){if(mec.getModifiers()==mec.BUTTON3_MASK){popupmenu.show(ta1,mec.getX(),mec.getY());}}public void mousePressed(MouseEvent ms){}public void mouseReleased(MouseEvent md){}public void mouseEntered(MouseEvent ms){}public void mouseExited(MouseEvent mex){}public void mouseDragged(MouseEvent med){}}public class Calculator {public static void main(String[] args) {// TODO Auto-generated method stubCal jishuanji=new Cal("计算器");}}。
JavaSwing实现仿win7计算器
JavaSwing实现仿win7计算器⾸先说明此代码的界⾯布局基本上参考了:由于后⾯的运算符处理操作实在难以理解。
所以后⾯事件的处理是⾃⼰改写的,我觉得这样⽐较好理解。
/****/package myJavaSwing;import javax.swing.JFrame;import java.awt.event.ActionListener;import java.awt.event.ActionEvent;import javax.swing.JButton;import javax.swing.JTextField;import javax.swing.JPanel;import java.awt.GridLayout;import java.awt.Color;import java.awt.BorderLayout;import java.awt.Container;/*** @author 花花*简介:仿windows7计算器*由于M键设计到存储器暂不⽀持M键的功能**/public class Calculator extends JFrame implements ActionListener {//计算器的三个功能键名字private final String COMMAND[]= {"Backspace","CE","C"};//计算计算⾯板上的键名private final String CALCULATE[]= {"7","8","9","/","sqrt","4","5","6","*","%","1","2","3","-","1/x","0","+/-",".","+","="};//计算器上的M键名private final String M[]= {" ","MC","MR","MS","M+"};//定义三个功能按钮JButton commands[]=new JButton[COMMAND.length];//定义计算⾯板班的按钮JButton calculate[]=new JButton[CALCULATE.length];//定义M按钮JButton m[]=new JButton[M.length];//结果⽂本框JTextField resultText=new JTextField();//计算结果private double result=0;//⽂本框中之前是否有输⼊private Boolean preferExist=false;//操作符private String op="=";//是否按了操作符private Boolean operate=false;//中间值。
简单的java代码例子
简单的java代码例子1. 使用Java实现一个简单的计算器,可以进行加减乘除运算。
```javaimport java.util.Scanner;public class Calculator {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);System.out.print("请输入第一个数:");double num1 = scanner.nextDouble();System.out.print("请输入运算符(+、-、*、/):");String operator = scanner.next();System.out.print("请输入第二个数:");double num2 = scanner.nextDouble();double result = 0;switch (operator) {case "+":result = num1 + num2;break;case "-":result = num1 - num2;break;case "*":result = num1 * num2;break;case "/":result = num1 / num2;break;default:System.out.println("输入的运算符不正确!");break;}System.out.println("计算结果为:" + result);}}```2. 使用Java实现一个简单的猜数字游戏,随机生成一个1-100之间的整数,让用户猜,直到猜中为止。
```javaimport java.util.Random;import java.util.Scanner;public class GuessNumber {public static void main(String[] args) {Random random = new Random();int number = random.nextInt(100) + 1;Scanner scanner = new Scanner(System.in);int guess;do {System.out.print("请输入你猜的数字(1-100):");guess = scanner.nextInt();if (guess > number) {System.out.println("猜大了!");} else if (guess < number) {System.out.println("猜小了!");}} while (guess != number);System.out.println("恭喜你,猜对了!");}}```3. 使用Java实现一个简单的学生信息管理系统,可以添加、删除、修改、查询学生信息。
java计算器代码
//计算器import java.awt.*;import java.awt.event.*;import javax.swing.*;public class Calculator extends WindowAdapter implements ActionListener{JFrame frame;JTextField show;JButton bc,ce,c,ab,jia,jian,cheng,chu,equ,point,sqrt,zf,bfh,ds;//退格,复位,清空,关于,加,减,乘,除,等,点,2,加减,百分之,倒数JButton b[]=new JButton[10];//保存数字JDialog about;final int length=30;int i=0,j=0,action=0,p=0; //记录数字键连续时间次数double num=0,getValue;//记录计算结果的值,保存值public Calculator(){frame=new JFrame("计算器");frame.addWindowListener(this);frame.setSize(360, 230);frame.setLocation(380,260);frame.setLayout(new FlowLayout(FlowLayout.CENTER));frame.setResizable(false);show=new JTextField(31);show.setText("0");show.setHorizontalAlignment(SwingConstants.RIGHT);show.setEnabled(false);frame.add(show);Panel dispTop=new Panel();frame.add(dispTop);dispTop.setLayout(new GridLayout(1,4,3,3));bc=new JButton("BACK");bc.addActionListener(this);dispTop.add(bc);ce=new JButton("CE");ce.addActionListener(this);dispTop.add(ce);c=new JButton("C");c.addActionListener(this);dispTop.add(c);ab=new JButton("ABOUT");ab.addActionListener(this);dispTop.add(ab);//about弹出框about=new JDialog(frame,"关于计算器",true);about.addWindowListener(this);JLabel label=new JLabel("",JLabel.CENTER); about.add(label);about.setSize(200,100);about.setLocation(500,300);//数据显示区Panel dispMain=new Panel();frame.add(dispMain);dispMain.setLayout(new GridLayout(1,2,10,10));//按钮左面板Panel dispLeft=new Panel();frame.add(dispLeft);dispLeft.setLayout(new GridLayout(4,3,3,3));//四行三列//按钮右面板Panel dispRight=new Panel();frame.add(dispRight);dispRight.setLayout(new GridLayout(4,2,3,3));//四行两列for(int l=9;l>=0;l--){b[l]=new JButton(String.valueOf(l));dispLeft.add(b[l]);b[l].addActionListener(this);}zf=new JButton("+/-");zf.addActionListener(this);dispLeft.add(zf);point=new JButton(".");point.addActionListener(this);dispLeft.add(point);chu=new JButton("/");chu.addActionListener(this);dispRight.add(chu);sqrt=new JButton("sqrt");sqrt.addActionListener(this);dispRight.add(sqrt);cheng=new JButton("*");cheng.addActionListener(this);dispRight.add(cheng);bfh=new JButton("%");bfh.addActionListener(this);dispRight.add(bfh);jian=new JButton("-");jian.addActionListener(this);dispRight.add(jian);ds=new JButton("1/x");ds.addActionListener(this);dispRight.add(ds);jia=new JButton("+");jia.addActionListener(this);dispRight.add(jia);equ=new JButton("=");equ.addActionListener(this);dispRight.add(equ);frame.setVisible(true);}//计算器抽象会报错public void actionPerformed(ActionEvent e){getValue=Double.valueOf(show.getText()).doubleValue();for(int k=0;k<10;k++){if(e.getSource()==b[k]){if(i==0){show.setText("");}String str=show.getText();if(str.length()<length){show.setText(show.getText()+e.getActionCommand());}i++;}}if(e.getSource()==jia){if(j==0){num=getValue;}else if(action==1){num+=getValue;}show.setText(String.valueOf(num));j++;action=1;i=0;////}else if(e.getSource()==jian){if(j==0){num=getValue;}else if(action==2){num-=getValue;}show.setText(String.valueOf(num));j++;action=2;i=0;///}else if(e.getSource()==cheng){if(j==0){num=getValue;}else if(action==3){num*=getValue;}show.setText(String.valueOf(num));j++;action=3;i=0;////}else if(e.getSource()==chu){if(j==0){num=getValue;}else if(action==4){num/=getValue;}show.setText(String.valueOf(num));j++;action=4;i=0;////}else if(e.getSource()==equ){switch(action){case 1:show.setText(String.valueOf(num+getValue));break;case 2:show.setText(String.valueOf(num-getValue));break;case 3:show.setText(String.valueOf(num*getValue));break;case 4:show.setText(String.valueOf(num/getValue));break;}//show.setText(String.valueOf(num));j=0;action=0;p=0;i=0;}else if(e.getSource()==point){if(p==0){show.setText(show.getText()+e.getActionCommand());p=1;}}else if(e.getSource()==ce||e.getSource()==c){j=0;action=0;p=0;num=0;i=0;////show.setText("0");}else if(e.getSource()==bc){String str=show.getText();if(str.length()>1){show.setText("");for(int t=0;t<str.length()-1;t++){char c=str.charAt(t);show.setText(show.getText()+c);}}else{show.setText("0");}}else if(e.getSource()==ab){about.setVisible(true);}else if(e.getSource()==sqrt){num=Math.sqrt(getValue);show.setText(String.valueOf(num));j++;i=0;///}else if(e.getSource()==ds){num=1/getValue;show.setText(String.valueOf(num));j++;i=0;////}else if(e.getSource()==bfh){num=getValue/100;show.setText(String.valueOf(num));j++;i=0;}else if(e.getSource()==zf){String str=show.getText();char c=str.charAt(0);if(c=='-'){show.setText("");for(int t=1;t<str.length();t++){show.setText(show.getText()+str.charAt(t));}}else{if(getValue!=0){show.setText("-"+show.getText());}}i=0;}}//windows关闭时调用此方法public void windowClosing(WindowEvent e){ if(e.getSource()==about){about.setVisible(false);}else if(e.getSource()==frame){System.exit(0);}}public static void main(String[] args) {Calculator c1=new Calculator();}}。
计算机程序源代码
import javax.swing.*;import java.awt.*;import javax.swing.border.*;import java.awt.event.*;public class SX7{JTextField field;JFrame f;JButton b;JLabel label;JPanel p1;JButton bb1,bb2,bb3;ActionListener h;Color cor1,cor2;Container con;GridBagLayout g;GridBagConstraints c;int gridx,gridy,gridwidth,gridheight,anchor,fill,ipadx,ipady;double weightx,weighty;Insets inset;Font t;boolean k1,/*控制字符的连续输出*/z,/*实现除零对其它按键的控制*/mh=true;/*保存控制显示*/ String op1,op2,r,ch,tf,str7,str11;Double r1,n1,n2,a,str8,str9,str10;int k,/*控制运算*/counter1,/*控制操作符*/counter2;/*控制连续运算*/SX7(){try{UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());}catch(Exception e){}makeJFrame();//添加JFrameaddmakeBarMenu();//添加菜单栏addButton();//添加组件f.setVisible(true);}private void addButton(){JPanel p=new JPanel();p1=new JPanel();p.setLayout(new GridLayout(1,4,3,6));p1.setLayout(new GridLayout(4,6,3,6));g=new GridBagLayout();con.setLayout(g);anchor=GridBagConstraints.CENTER;//当组件小于其显示区域时使用此字段。
eclipse实现简单计算器代码.
eclipse实现简单计算器代码.package Computer;import java.awt.*;import java.awt.event.*;import javax.swing.*;import javax.swing.border.*;import java.util.LinkedList;import java.text.NumberFormat;public class Cacultor extends Frame implements ActionListener{/*** @param args*/NumberButton numberButton[];OperationButton operationButton[];Button 小数点按钮,正负号按钮,退格按钮,求倒数按钮,等号按钮,清零按钮;Panel panel;JTextField resultShow;String 运算符号[]={"+","-","*","/"};LinkedList 链表;boolean 是否按下等号=false;public Cacultor(){super("计算器");链表=new LinkedList();numberButton=new NumberButton[10];for(int i=0;i<=9;i++){numberButton[i]=new NumberButton(i);numberButton[i].addActionListener(this);}operationButton=new OperationButton[4];for(int i=0;i<4;i++){operationButton[i]=new OperationButton(运算符号[i]);operationButton[i].addActionListener(this);}小数点按钮=new Button(".");正负号按钮=new Button("+/-");等号按钮=new Button("=");求倒数按钮=new Button("1/x");退格按钮=new Button("退格");清零按钮=new Button("c");清零按钮.setForeground(Color.red);退格按钮.setForeground(Color.red);等号按钮.setForeground(Color.red);求倒数按钮.setForeground(Color.blue);正负号按钮.setForeground(Color.blue);小数点按钮.setForeground(Color.blue);退格按钮.addActionListener(this);清零按钮.addActionListener(this);等号按钮.addActionListener(this);小数点按钮.addActionListener(this);正负号按钮.addActionListener(this);求倒数按钮.addActionListener(this);resultShow=new JTextField(10);resultShow.setHorizontalAlignment(JTextField.RIGHT); resultShow.setForeground(Color.blue);resultShow.setFont(new Font("TimesRoman",Font.PLAIN,14)); resultShow.setBorder(newSoftBevelBorder(BevelBorder.LOWERED));resultShow.setBackground(Color.white);resultShow.setEditable(false);panel=new Panel();panel.setLayout(new GridLayout(4,5));panel.add(numberButton[1]);panel.add(numberButton[2]);panel.add(numberButton[3]);panel.add(operationButton[0]);panel.add(清零按钮);panel.add(numberButton[4]);panel.add(numberButton[5]);panel.add(numberButton[6]);panel.add(operationButton[1]);panel.add(退格按钮);panel.add(numberButton[7]);panel.add(numberButton[8]);panel.add(numberButton[9]);panel.add(operationButton[2]);panel.add(求倒数按钮);panel.add(numberButton[0]);panel.add(正负号按钮);panel.add(小数点按钮);panel.add(operationButton[3]);panel.add(等号按钮);add(panel,BorderLayout.CENTER);add(resultShow,BorderLayout.NORTH);addWindowListener(new WindowAdapter(){public void windowClosing(WindowEvent e){ System.exit(0);}});setVisible(true);setBounds(100,50,240,180);setResizable(false);validate();}//按钮事件的处理public void actionPerformed(ActionEvent e){if(e.getSource() instanceof NumberButton){NumberButton b=(NumberButton)e.getSource();if(链表.size()==0){int number=b.getNumber();链表.add(""+number);resultShow.setText(""+number);是否按下等号=false;}else if(链表.size()==1&&是否按下等号==false){ int number=b.getNumber();String num=(String)链表.getFirst();String s=num.concat(""+number);链表.set(0, s);resultShow.setText(s);}else if(链表.size()==1&&是否按下等号==true){int number=b.getNumber();链表.removeFirst();链表.add(""+number);是否按下等号=false;resultShow.setText(""+number);}else if(链表.size()==2){int number=b.getNumber();链表.add(""+number);resultShow.setText(""+number);}else if(链表.size()==3){int number=b.getNumber();String num=(String)链表.getLast();String s=num.concat(""+number);链表.set(2, s);resultShow.setText(s);}}else if(e.getSource()instanceof OperationButton){ OperationButton b=(OperationButton)e.getSource();if(链表.size()==1){String fuhao=b.get运算符号();链表.add(fuhao);}else if(链表.size()==2){String fuhao=b.get运算符号();链表.set(1, fuhao);}else if(链表.size()==3){String fuhao=b.get运算符号();String number1=(String)链表.getFirst();String number2=(String)链表.getLast();String 运算符号=(String)链表.get(1);try{double n2=Double.parseDouble(number2); double n=0;if(运算符号.equals("+")){n=n1+n2;}else if(运算符号.equals("-")){n=n1-n2;}else if(运算符号.equals("*")){n=n1*n2;}else if(运算符号.equals("/")){n=n1/n2;}链表.clear();链表.add(""+n);链表.add(fuhao);resultShow.setText(""+n);}catch(Exception ee){}}}else if(e.getSource()==等号按钮){是否按下等号=true;if(链表.size()==1&&链表.size()==2){ String num=(String)链表.getFirst(); resultShow.setText(""+num);}else if(链表.size()==3){String number1=(String)链表.getFirst(); String number2=(String)链表.getLast(); String 运算符号=(String)链表.get(1);try{double n2=Double.parseDouble(number2); double n=0;if(运算符号.equals("+")){n=n1+n2;}else if(运算符号.equals("-")){n=n1-n2;}else if(运算符号.equals("*")){n=n1*n2;}else if(运算符号.equals("/")){n=n1/n2;}resultShow.setText(""+n);链表.set(0, ""+n);链表.removeLast();链表.removeLast();}catch(Exception ee){}}}else if(e.getSource()==小数点按钮){if(链表.size()==0){是否按下等号=false;}else if(链表.size()==1){String dot=小数点按钮.getLabel();String num=(String)链表.getFirst();String s=null;if(num.indexOf(dot)==-1){s=num.concat(dot);链表.set(0, s);}else{s=num;}链表.set(0, s);resultShow.setText(s);}else if(链表.size()==3){String dot=小数点按钮.getLabel(); String num=(String)链表.getLast(); String s=null;if(num.indexOf(dot)==-1){s=num.concat(dot);链表.set(2, s);}else{s=num;}resultShow.setText(s);}}else if(e.getSource()==退格按钮){if(链表.size()==1){String num=(String)链表.getFirst();if(num.length()>=1){num=num.substring(0,num.length()-1); 链表.set(0, num);resultShow.setText(num);}else{链表.removeLast();resultShow.setText("0");}}else if(链表.size()==3){String num=(String)链表.getLast();if(num.length()>=1){num=num.substring(0,num.length()-1); 链表.set(2, num);resultShow.setText(num);}else{链表.removeLast();resultShow.setText("0");}}}else if(e.getSource()==正负号按钮){if(链表.size()==1){String number1=(String)链表.getFirst(); try{double d=Double.parseDouble(number1); d=-1*d;String str=String.valueOf(d);链表.set(0, str);resultShow.setText(str);}catch(Exception ee){}}else if(链表.size()==3){String number2=(String)链表.getLast();try{double d=Double.parseDouble(number2); d=-1*d;String str=String.valueOf(d);链表.set(2, str);resultShow.setText(str);}catch(Exception ee){}}}else if(e.getSource()==求倒数按钮){if(链表.size()==1||链表.size()==2){String number1=(String)链表.getFirst(); try{double d=Double.parseDouble(number1); d=1.0/d;String str=String.valueOf(d);链表.set(0, str);resultShow.setText(str);}catch(Exception ee){}}else if(链表.size()==3){String number2=(String)链表.getLast();try{double d=Double.parseDouble(number2); d=1.0/d;String str=String.valueOf(d);链表.set(0, str);resultShow.setText(str);}catch(Exception ee){}}}else if(e.getSource()==清零按钮){是否按下等号=false;resultShow.setText("0");链表.clear();}}public static void main(String[] args) {// TODO Auto-generated method stub new Cacultor();}}。
java编写的计算器设计报告
java编写的计算器设计报告实验7:综合实验二一、试验目的进一步掌握图形用户界面GUI,了解Swing组件的使用,以及系统提供的该工具的作用,进一步掌握JAVA事件响应机制的原理,更好的掌握面向对象编程的思路。
二、实验要求创建一个界面来实现一个简单的计算器,要求:1、实现最基本的计算器界面,包括:0~9的10个数字按钮,加、减、乘、除、等于5个运算符按钮,一个结果存放的文本区域。
2、实现最基本的加、减、乘、除运算,并能得到正确结果。
3、实现连续的运算,小数点的使用,并考虑各种可能导致异常的情况,将程序作完善;4、可以通过关闭按钮实现关闭窗口。
三、实验步骤、结果1、程序代码:import java.awt.BorderLayout;import java.awt.GridLayout;import java.awt.event.ActionEvent; importjava.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JPanel;import javax.swing.JTextField;import javax.swing.SwingConstants;public class ZhxCacu extends JFrame implements ActionListener { JPanel jpResult = new JPanel();JPanel jpButton = new JPanel();JTextField jtfResult = new JTextField("0");JButton zero = new JButton("0"); //数字键0JButton one = new JButton("1"); //数字键1JButton two = new JButton("2"); //数字键2JButton three = new JButton("3"); //数字键3JButton four = new JButton("4"); //数字键4JButton five = new JButton("5"); //数字键5JButton six = new JButton("6"); //数字键6JButton seven = new JButton("7"); //数字键7JButton eight = new JButton("8"); //数字键8JButton nine = new JButton("9"); // 数字键9JButton plus = new JButton("+");JButton sub = new JButton("-");JButton mul = new JButton("*");JButton div = new JButton("/");JButton equal = new JButton("=");JButton ce = new JButton("ce"); // 置零键JButton point = new JButton(".");JButton tzero = new JButton("00");//com代表敲击运算符,digit代表敲击数字键boolean com = false;boolean digit = false;float total=0;String sum="";int symbol=0;int b,c=0;public ZhxCacu(){// 添加结果输入框并设置对齐方式jpResult.setLayout(new BorderLayout());jpResult.add(jtfResult);jtfResult.setEditable(false);jtfResult.setHorizontalAlignment(SwingConstants.RIGHT); //将组件添加到窗体上this.add(jpResult,"North");this.add(jpButton,"Center");// 定义按钮区域布局管理器为网格布局jpButton.setLayout(new GridLayout(6, 3, 10, 10));// 添加各个按钮键jpButton.add(seven);jpButton.add(eight);jpButton.add(nine);jpButton.add(four);jpButton.add(five);jpButton.add(six);jpButton.add(one);jpButton.add(two);jpButton.add(three);jpButton.add(zero);jpButton.add(tzero);jpButton.add(plus);jpButton.add(sub);jpButton.add(mul);jpButton.add(div);jpButton.add(point);jpButton.add(equal);jpButton.add(ce);one.addActionListener(this);//对1按钮添加监听事件two.addActionListener(this);//对2按钮添加监听事件three.addActionListener(this);//对3按钮添加监听事件four.addActionListener(this);//对4按钮添加监听事件five.addActionListener(this);//对5按钮添加监听事件six.addActionListener(this);//对6按钮添加监听事件seven.addActionListener(this);//对7按钮添加监听事件eight.addActionListener(this);//对8按钮添加监听事件nine.addActionListener(this);//对9按钮添加监听事件zero.addActionListener(this);//对0按钮添加监听事件ce.addActionListener(this);//对置零按钮添加监听事件plus.addActionListener(this);//对+按钮添加监听事件equal.addActionListener(this);//对=按钮添加监听事件sub.addActionListener(this);//对-按钮添加监听事件mul.addActionListener(this);//对*按钮添加监听事件div.addActionListener(this);//对/按钮添加监听事件tzero.addActionListener(this);//对00按钮添加监听事件point.addActionListener(this);//对.按钮添加监听事件pack();//初始化窗体大小最合适大小this.addWindowListener(new WindowAdapter(){public void windowClosing(WindowEvent e){System.exit(0);}});this.setSize(300,300);this.setVisible(true);}public static void main(String[] args) {// TODO 自动生成方法存根new ZhxCacu();}public void actionPerformed(ActionEvent e) {// TODO 自动生成方法存根//数字if(e.getSource()==one){if(com||digit==false){//第一次敲击数字按钮jtfResult.setText("1");com = false;digit = true;}else{sum = jtfResult.getText()+"1"; jtfResult.setText(sum);}}else if(e.getSource()==two){if(com||digit==false){//第一次敲击数字按钮jtfResult.setText("2");com = false;digit = true;}else{sum = jtfResult.getText()+"2"; jtfResult.setText(sum);}}else if(e.getSource()==two){if(com||digit==false){//第一次敲击数字按钮jtfResult.setText("2");com = false;digit = true;}else{sum = jtfResult.getText()+"2"; jtfResult.setText(sum);}}else if(e.getSource()==two){if(com||digit==false){//第一次敲击数字按钮jtfResult.setText("2");com = false;digit = true;}else{sum = jtfResult.getText()+"2"; jtfResult.setText(sum);}}else if(e.getSource()==two){if(com||digit==false){//第一次敲击数字按钮jtfResult.setText("2");com = false;digit = true;}else{sum = jtfResult.getText()+"2"; jtfResult.setText(sum);}}else if(e.getSource()==three){if(com||digit==false){//第一次敲击数字按钮jtfResult.setText("3");com = false;digit = true;}else{sum = jtfResult.getText()+"3"; jtfResult.setText(sum);}}else if(e.getSource()==four){if(com||digit==false){//第一次敲击数字按钮jtfResult.setText("4");com = false;digit = true;}else{sum = jtfResult.getText()+"4"; jtfResult.setText(sum);}}else if(e.getSource()==five){if(com||digit==false){//第一次敲击数字按钮jtfResult.setText("5");com = false;digit = true;}else{sum = jtfResult.getText()+"5"; jtfResult.setText(sum);}}else if(e.getSource()==six){if(com||digit==false){//第一次敲击数字按钮jtfResult.setText("6");com = false;digit = true;}else{sum = jtfResult.getText()+"6"; jtfResult.setText(sum);}}else if(e.getSource()==seven){if(com||digit==false){//第一次敲击数字按钮jtfResult.setText("7");com = false;digit = true;}else{sum = jtfResult.getText()+"7";jtfResult.setText(sum);}}else if(e.getSource()==eight){if(com||digit==false){//第一次敲击数字按钮jtfResult.setText("8");com = false;digit = true;}else{sum = jtfResult.getText()+"8"; jtfResult.setText(sum);}}else if(e.getSource()==nine){if(com||digit==false){//第一次敲击数字按钮jtfResult.setText("9");com = false;digit = true;}else{sum = jtfResult.getText()+"9"; jtfResult.setText(sum);}}else if(e.getSource()==zero){if(com||digit==false){//第一次敲击数字按jtfResult.setText("0");com = false;digit = true;}else{sum = jtfResult.getText()+"0"; jtfResult.setText(sum);if(Float.parseFloat(sum)!=0){}else{if(b==1){sum = jtfResult.getText()+"0"; jtfResult.setText(sum);}elsejtfResult.setText("0");}}}else if(e.getSource()==tzero){if(com||digit==false){//第一次敲击数字按jtfResult.setText("00");com = false;digit = true;}else{sum = jtfResult.getText()+"00";jtfResult.setText(sum);}}else if(e.getSource()==point){if(com||digit==false){//第一次敲击数字按钮b=1;com = true;digit = false;}else if(c==1); else{b=1;sum = jtfResult.getText()+".";jtfResult.setText(sum);c=1;}}//运算else if(e.getSource()==plus){symbol = 1;c=0;total = Float.parseFloat(jtfResult.getText()); com = true;digit = false;}else if(e.getSource()==sub){symbol = 2;c=0;total = Float.parseFloat(jtfResult.getText()); com = true;digit = false;}else if(e.getSource()==mul){symbol = 3;c=0;total = Float.parseFloat(jtfResult.getText()); com = true;digit = false;}else if(e.getSource()==div){symbol = 4;c=0;total = Float.parseFloat(jtfResult.getText()); com = true;digit = false;}else if(e.getSource()==ce){com = true;digit = false;total=0;sum ="0" ;jtfResult.setText(sum);}//=else if(e.getSource()==equal){com = true;digit = false;switch(symbol){case 1:jtfResult.setText(newFloat(total+Float.parseFloat(jtfResult.getText())).toString());b=0;c=0;b reak;case 2:jtfResult.setText(newFloat(total-Float.parseFloat(jtfResult.getText())).toString());b=0;c=0;break;case 3:jtfResult.setText(newFloat(total*Float.parseFloat(jtfResult.getText())).toString());b=0;c =0;break;case 4:if( Float.parseFloat(jtfResult.getText())==0 ){try{throw new Exception();}catch(Exception a){jtfResult.setText("错误~被除数不能为0,请重新输入:");}}elsejtfResult.setText(newFloat(total/Float.parseFloat(jtfResult.getText())).toString());b=0;c =0;break;}digit=false;total = 0;}}}2、界面:四、实验中的问题以及解决方案:1、问题: 被除数为0解决:抛出异常2、问题: 阻止0、小数点在同一数字中重复出现解决: 设置标志,五、总结:1、进一步了解了项目开发的步骤,思路,以及程序的布局和框架结构,尤其是对JAVA的模块化设计有了更为深入的了解。
JAVA计算器源代码
计算器源代码一、计算器源代码文件名:computer1.javaimport java.awt.*;import java.awt.event.*;public class computer1 extends Frame implements ActionListener{//声明窗口类并实现动作事件接口。
Button n0,n1,n2,n3,n4,n5,n6,n7,n8,n9;//声明数字按钮Button op,os,om,od,oe,oc;//声明操作按钮TextField tfd;//声明文本框String flg,rslt;//声明标志串、结果串Panel p1,p2,p3;//声明面板int i1,i2;float flt;computer1(){super("加减乘除计算器");n0 = new Button("0");//实现各按钮n1 = new Button("1");n2 = new Button("2");n3 = new Button("3");n4 = new Button("4");n5 = new Button("5");n6 = new Button("6");n7 = new Button("7");n8 = new Button("8");n9 = new Button("9");op = new Button("加");os = new Button("减");om = new Button("乘");od = new Button("除");oe = new Button("=");oc = new Button("c");tfd = new TextField(20);//实现文本框p1=new Panel();//实现各面板p2=new Panel();p3=new Panel();setLayout(new FlowLayout());//布局设计,用于安排按钮位置p1.add(n0);//将各数字按钮放入p1中p1.add(n1);p1.add(n2);p1.add(n3);p1.add(n4);p1.add(n5);p1.add(n6);p1.add(n7);p1.add(n8);p1.add(n9);p2.add(op);//将各操作按钮放入p2、p3中p2.add(os);p2.add(om);p2.add(od);p3.add(oe);p3.add(oc);setLayout(new BorderLayout());//布局设计,用于安排面板位置add("North",tfd);add("West",p1);add("Center",p2);add("East",p3);n0.addActionListener(this);//注册监听器到各按钮n1.addActionListener(this);n2.addActionListener(this);n3.addActionListener(this);n4.addActionListener(this);n5.addActionListener(this);n6.addActionListener(this);n7.addActionListener(this);n8.addActionListener(this);n9.addActionListener(this);op.addActionListener(this);os.addActionListener(this);om.addActionListener(this);od.addActionListener(this);oe.addActionListener(this);oc.addActionListener(this);addWindowListener(new closeWin());setSize(600,100);//确定窗口的尺寸setVisible(true);}public static void main (String args[]){new computer1();}public void actionPerformed(ActionEvent e){//处理鼠标事件的方法try{//异常处理if(e.getSource()==n0)//按数字键时tfd.setText(tfd.getText()+"0");if(e.getSource()==n1)tfd.setText(tfd.getText()+"1");if(e.getSource()==n2)tfd.setText(tfd.getText()+"2");if(e.getSource()==n3)tfd.setText(tfd.getText()+"3");if(e.getSource()==n4)tfd.setText(tfd.getText()+"4");if(e.getSource()==n5)tfd.setText(tfd.getText()+"5");if(e.getSource()==n6)tfd.setText(tfd.getText()+"6");if(e.getSource()==n7)tfd.setText(tfd.getText()+"7");if(e.getSource()==n8)tfd.setText(tfd.getText()+"8");if(e.getSource()==n9)tfd.setText(tfd.getText()+"9");if(e.getSource()==op){//按加号键时i1 = Integer.parseInt(tfd.getText());tfd.setText("");flg = "op";}if(e.getSource()==os){//按减号键时i1 = Integer.parseInt(tfd.getText());tfd.setText("");flg = "os";}if(e.getSource()==om){//按乘号键时i1 = Integer.parseInt(tfd.getText());tfd.setText("");flg = "om";}if(e.getSource()==od){//按除号键时i1 = Integer.parseInt(tfd.getText());tfd.setText("");flg = "od";}if(e.getSource()==oe){//按等号键时i2 = Integer.parseInt(tfd.getText());if(flg=="op"){rslt=Integer.toString(i1+i2);}if(flg=="os"){rslt=Integer.toString(i1-i2);}if(flg=="om"){rslt=Integer.toString(i1*i2);}if(flg=="od"){//除法需做小数处理flt=((float)i1)/((float)i2);rslt=Float.toString(flt);}tfd.setText(rslt);}if(e.getSource()==oc){//按清除键时tfd.setText("");flg = "";}}catch(Exception ex){}//扑捉到异常,但不进行处理}}class closeWin extends WindowAdapter{ //关闭窗口public void windowClosing(WindowEvent e){Frame frm=(Frame)(e.getSource());frm.dispose();System.exit(0);}}二、计算器界面三、修改后计算器界面。
java简易计算器完整代码
java简易计算器完整代码import java.awt.BorderLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JOptionPane;import javax.swing.JPanel;import javax.swing.JTextField;public class Calculate extends JFrame implements ActionListener {/****/private static final long serialVersionUID = 1L;/*** @param args*/float userFloata=0f;float userFloatb=0f;double result;JLabel label1 ;JLabel label2;JLabel label3;JTextField textField1;JTextField textField2;JTextField textField3;JButton addButton;JButton subtractButton;JButton rideButton;JButton divideButton;public Calculate(){setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);setTitle("简易计算器");JPanel viewJPanel_1=new JPanel();JPanel viewJPanel_2=new JPanel();addButton=new JButton("加");addButton.addActionListener(this);viewJPanel_1.add(addButton);subtractButton=new JButton("减");subtractButton.addActionListener(this);viewJPanel_1.add(subtractButton);rideButton=new JButton("乘");rideButton.addActionListener(this);viewJPanel_1.add(rideButton);divideButton=new JButton("除");divideButton.addActionListener(this);viewJPanel_1.add(divideButton);label1=new JLabel("数据1:");viewJPanel_2.add(label1);textField1=new JTextField(5);textField1.addActionListener(this);viewJPanel_2.add(textField1);label2=new JLabel("数据2:");viewJPanel_2.add(label2);textField2=new JTextField(5);textField2.addActionListener(this);viewJPanel_2.add(textField2);label3=new JLabel("结果是:");viewJPanel_2.add(label3 );textField3=new JTextField(5);viewJPanel_2.add(textField3);setSize(420,120);setVisible(true);validate();getContentPane().add(viewJPanel_1,BorderLayout.NORTH);getContentPane().add(viewJPanel_2,BorderLayout.CENTER);}public void CalculateEventHandel(){try{userFloata= Float.parseFloat(textField1.getText().trim());userFloatb= Float.parseFloat(textField2.getText().trim());} catch (NumberFormatException e) {JOptionPane.showMessageDialog(this, "请输入数字型数据!");textField1.setText("");textField1.requestFocus();textField2.setText("");textField3.setText("");return;}}public static void main(String[] args) { // TODO Auto-generated method stubnew Calculate();//a.CalculateEventHandel();}public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stubif(e.getSource()==addButton){this.CalculateEventHandel();result=userFloata+userFloatb;// System.out.println(""+result);textField3.setText(""+result);}else if(e.getSource()==subtractButton){ this.CalculateEventHandel();result=userFloata-userFloatb;textField3.setText(""+result);}else if(e.getSource()==rideButton){this.CalculateEventHandel();result=userFloata*userFloatb;textField3.setText(""+result);}else if(e.getSource()==divideButton){this.CalculateEventHandel();result=userFloata/userFloatb;textField3.setText(""+result);}}}。
自己写的计算器(加减乘除)代码
⾃⼰写的计算器(加减乘除)代码⾸先是Calculator计算器类package zydCalr;public class Calculator {public double addition(double number1, double number2) {return number1+number2;}public double subtraction(double number1, double number2) {return number1-number2;}public double multiplication(double number1, double number2) {return number1*number2;}public double divsition(double number1, double number2) {return number1/number2;}}接下来是Execute运⾏类package zydCalr;import java.util.Scanner;public class Execution {public double execute(String str){String expression = str + "+1";// 初始化开始//char[] Cexpression = expression.toCharArray();// 创建运算器Calculator calculator = new Calculator();// 数值列表double[] numbers = new double[30];int numbersindex = 0;// 转型列表char[] sub = new char[30];// 数值下标位置int count = 0;// 符号列表char[] symbols = new char[10];int symbolsindex = 0;// temp1是数值列表上⼀个数值,temp2是当前的数值double temp1 = 0, temp2 = 0;;// 符号char symbol = 0;int flag = 1;// 初始化结束// 第⼀次遍历for (int i = 0; i < expression.length(); i++) {if (Cexpression[i] >= '0' && sub[i] <= '9') {sub[count++] = Cexpression[i];} else {// 字符串转型doubletemp2 = transition(sub,count);// 当flag=2时进⾏运算if (flag == 2) {flag = 1;// 获取数值列表前⼀个数值;temp1 = numbers[numbersindex - 1];// 判断symbol乘法还是除法,成功是乘法,失败为除法if (decide(symbol)==1) {temp2 = calculator.multiplication(temp1, temp2);} else {temp2 = calculator.divsition(temp1, temp2);}// 覆盖前⼀个数值numbersindex--;}// temp2存⼊数值列表numbers[numbersindex++] = temp2;// 获取符号symbol = Cexpression[i];// 转型数值下标位置清零count = 0;// 判断是否⼤于flag,flag=2,不⼤于则加⼊到符号列表if (judge(symbol) > flag) {flag = 2;} else {// 加⼊到符号列表symbols[symbolsindex++] = symbol;}}}double temp = numbers[0];count = 0;for (int i = 1; i < numbers.length; i++) {if (symbols[count] == '+') {temp += numbers[i];count++;} else if (symbols[count] == '-') {temp -= numbers[i];count++;}}return temp;}private static int judge(char symbol) {if (symbol == '+') {return 1;} else if (symbol == '-') {return 1;} else if (symbol == '*') {return 2;} else if (symbol == '/') {return 2;}return 0;}private static int decide(char symbol) {if (symbol == '*') {return 1;} else if (symbol == '/') {return 2;}return 2;}private static int transition(char[] sub1,int count) {int temp = 0;for (int i = 0; i < count; i++) {if (sub1[i] >= '0' && sub1[i] <= '9') {temp = temp * 10;temp += (sub1[i] - '0');}}return temp;}}产⽣表达式类package zydCalr;import java.util.Random;public class ProductionExpression {//⽣成数值public static String producerNumber() {int number = (int) (Math.random() * 50);return String.valueOf(number);}//⽣成数值public static String producerOpreator() {int number = (int) (Math.random() * 4);String[] operator = { "+", "-", "*", "/" };return operator[number];}//产⽣public static String producer(int i) {StringBuilder sb = new StringBuilder();int flag = (int) (Math.random() * 5);if(flag==1){sb.append("-");}sb.append(producerNumber());while (i > 0) {sb.append(producerOpreator());sb.append(producerNumber());i--;}return sb.toString();}//产⽣表达式public static String producerExpression() {int lenght = (int) (Math.random() * 5);if (lenght % 2 == 0) {lenght++;}String expression = producer(lenght);return expression;}}⽣产者类package zydCalr;import java.util.ArrayList;import java.util.List;public class Producer implements Runnable {static final int MAXQUEUE = 5;private List<String> messages = new ArrayList<String>(); private ProductionExpression pe=new ProductionExpression(); @Overridepublic void run() {// TODO Auto-generated method stubwhile (true) {putMessage();try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}}}private synchronized void putMessage() {while (messages.size() >= MAXQUEUE) {try {wait();} catch (InterruptedException e) {e.printStackTrace();}}//⽣成表达式messages.add(pe.producerExpression());notify();}public synchronized String getMessage() {while (messages.size() == 0) {try {notify();wait();} catch (InterruptedException e) {e.printStackTrace();}}String message = (String) messages.remove(0);notify();return message;}}消费者类package zydCalr;public class Consumer implements Runnable {Producer producer;Consumer(Producer producer) {this.producer = producer;}public void run() {while (true) {System.out.println("-------------开始⼀组表达式处理-------------");String message = producer.getMessage();System.out.println("⽣成表达式:" + message);Execution exe=new Execution();System.out.printf("处理结果:"+"%.2f\n",exe.execute(message));try {Thread.sleep(2000);} catch (InterruptedException e) {e.printStackTrace();}}}public static void main(String[] args) {Producer producer = new Producer();new Thread(producer).start();Consumer consumer = new Consumer(producer);new Thread(consumer).start();}}代码还是很简单的,主要有两个列表,⼀个列表存数值,⼀个列表存符号,如果符号是乘法或者除法,则把当前的数值和数值列表最后的数值相乘或相除,然后覆盖到数字列表的最后,如果不是,则存⼊数值列表的最后,符号列表添加当前的减法或者乘法,最后我发现许多细节的东西没有处理。
Java计算器实验报告(包括普通型和科学型)
一、计算器实验报告一、实验名称及其要求:A)名称: java计算器的设计B)要求:1.实验目的:图形界面设计。
熟悉java.awt包中的组件,掌握图形界面设计方法,理解委托事件处理模型。
2.题意:请设计并实现Windows系统中“计算器”的窗口及功能。
3.实验要求:(1)设计图形界面添加菜单:窗口上添加各种组件及菜单,并处理组件及菜单的事件监听程序。
(2)运算:实现多种运算,保证运算正确性。
二、实验步骤先新建两个类,一个类是普通型计算器的Count1,另一个类是科学性计算器的Count2一)、普通型计算器1、先利用Java各种图形组件完成计算的整体界面,在界面中添加按钮以及菜单项,如图①先定义各按钮以及菜单、菜单项JPanel p2= new JPanel();JTextField jt2 = new JTextFiled();JMenuBar jmb = new JMenuBar () ;JMenu check = new JMenu ("查看(V)") ;JMenu edit = new JMenu ("编辑(E)") ;JMenu help = new JMenu ("帮助(H)") ;JMenuItem help_about = new JMenuItem("关于") ;JMenuItem help_help = new JMenuItem("操作说明") ;JMenuItem exit = new JMenuItem("退出") ;JRadioButton rb2 = new JRadioButton("标准型",true) ;JRadioButton rb1 = new JRadioButton("科学型") ;ButtonGroup bg = new ButtonGroup() ;按钮的定义形式如下:JButton b = new JButton(”i”),i表示各按钮上的字符将各按钮添加到面板p2中至于添加按钮进面板的由于比较简单,这里就不做说明了。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
p6.add(tf2); p3.add(p6); p3.add(bMC); p3.add(bMR); p3.add(bMS); p3.add(bM);
前输入值?
Frame f; Panel p1, p2, p3, p4, p5, p6; TextField tf1, tf2; Button b1, b2, b3, b4, b5, b6, b7, b8, b9, b0; Button bDiv, bSqrt, bMulti, bMinus, bPercent, bPlus, bReciprocal, bEqual,
bDiv.addActionListener(this); bSqrt.addActionListener(this); bMulti.addActionListener(this); bMinus.addActionListener(this); bPercent.addActionListener(this); bPlus.addActionListener(this); bReciprocal.addActionListener(this); bEqual.addActionListener(this); bDot.addActionListener(this); bNegative.addActionListener(this);
bBackspace = new Button("Backspace"); bCE = new Button("CE"); bC = new Button("C");
bBackspace.addActionListener(this);
bCE.addActionListener(this); bC.addActionListener(this);
b1 = new Button("1"); b2 = new Button("2"); b3 = new Button("3"); b4 = new Button("4"); b5 = new Button("5"); b6 = new Button("6"); b7 = new Button("7"); b8 = new Button("8"); b9 = new Button("9"); b0 = new Button("0");
f.setLayout(new BorderLayout(3, 3));
p1 = new Panel(new GridLayout(1, 3, 5, 5)); // 用于存放 backspace,ce,c 三键 p2 = new Panel(new GridLayout(4, 5, 5, 5)); // 用于存放数字区及附近共 20 键,
else { double temp = Double.parseDouble(e.getActionCommand()); for (int i = this.n; i < 0; i++) { temp *= 0.1; } this.dNowInput += temp; this.n--;
} this.tf1.setText(Double.toString(this.dNowInput)); } // key dot if (this.keyAvailable && e.getActionCommand() == ".") { if (this.alreadyHaveDot == false) {
p1.add(bBackspace); p1.add(bCE); p1.add(bC);
tf2 = new TextField(2); tf2.setEnabled(false); bMC = new Button("MC"); bMR = new Button("MR"); bMS = new Button("MS"); bM = new Button("M+");
b1.addActionListener(this); b2.addActionListener(this); b3.addActionListener(this); b4.addActionListener(this); b5.addActionListener(this); b6.addActionListener(this); b7.addActionListener(this); b8.addActionListener(this); b9.addActionListener(this); b0.addActionListener(this);
bDiv = new Button("/"); bSqrt = new Button("sqrt"); bMulti = new Button("*"); bMinus = new Button("-");
bPercent = new Button("%"); bPlus = new Button("+"); bReciprocal = new Button("1/x"); bEqual = new Button("="); bDot = new Button("."); bNegative = new Button("+/-");
package calculator;
import java.awt.*; import java.awt.event.*;
import javax.swing.JLabel; import javax.swing.JPanel;
public class calwin extends WindowAdapter implements ActionListener { private JLabel display; private JPanel numpanel,companel1,companel2; private double result; private String lastCommand; private boolean start; double dResult = 0; double dNowInput = 0; double dMemory; int n = 0; // 记载小数位数 int nOperation = 1; // 记录运算符类型 int nBitsNum = 0; // 记录总共输入的位数 boolean alreadyHaveDot = false; // 已经有小数点? boolean keyAvailable = true; boolean alreadyClickedEqueal = false; // 是否按下过"="? boolean isTempNowInput = false; // 是否在计算出结果后直接按运算符将结果赋给了当
tf1 = new TextField(35); // 存放显示区 tf1.setText("0."); tf1.setEditable(false); p5.add(tf1); f.add(p5, BorderLayout.NORTH); f.add(p4, BorderLayout.CENTER); f.add(p3, BorderLayout.WEST);
f.setVisible(true); f.addWindowListener(this);
}
public void actionPerformed(ActionEvent e) { // key 0 to 9 if (this.keyAvailable && e.getActionCommand().length() == 1 && e.getActionCommand().compareTo("0") >= 0 && e.getActionCommand().compareTo("9") <= 0) { if (this.isTempNowInput) { this.dNowInput = 0; this.isTempNowInput = false; } this.nBitsNum++; if (this.alreadyHaveDot == false) this.dNowInput = this.dNowInput * 10 + Double.parseDouble(e.getActionCommand());
this.nBitsNum++; this.alreadyHaveDot = true; this.n = -1; } } // key "+","-","*","/" if (this.keyAvailable && e.getActionCommand() == "+" || e.getActionCommand() == "-" || e.getActionCommand() == "*" || e.getActionCommand() == "/") { if (this.alreadyClickedEqueal) { this.dNowInput = this.dResult; this.isTempNowInput = true; } else { switch (this.nOperation) { case 1: