资源描述:
《计算器Java编程完全代码》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、计算器Java编程代码1、界面截图1、程序代码importjava.awt.*;importjava.awt.event.*;importjavax.swing.*;publicclassCounterimplementsActionListener{//改进小数问题privatebooleanappend=false;JButton[]jb=newJButton[20];JTextFieldjtf=newJTextField(19);String[]st={"Backs","CE","C","+","7","8","9","-","4","5","6","*","1"
2、,"2","3","/",".","+/-","0","=",};Stringnum1="0";Stringoperator="+";publicCounter(){JFramejf=newJFrame("计算器");//界面设置GridLayoutgl=newGridLayout(6,1);jf.setLayout(gl);JPaneljp0=newJPanel();4jp0.add(jtf);jf.add(jp0);JPaneljp1=newJPanel();for(inti=0;i<4;i++){jb[i]=newJButton(st[i]);jp1.add(jb
3、[i]);}jf.add(jp1);JPaneljp2=newJPanel();for(inti=4;i<8;i++){jb[i]=newJButton(st[i]);jp2.add(jb[i]);}jf.add(jp2);JPaneljp3=newJPanel();for(inti=8;i<12;i++){jb[i]=newJButton(st[i]);jp3.add(jb[i]);}jf.add(jp3);JPaneljp4=newJPanel();for(inti=12;i<16;i++){jb[i]=newJButton(st[i]);jp4.add(jb[i]
4、);}jf.add(jp4);JPaneljp5=newJPanel();for(inti=16;i<20;i++){jb[i]=newJButton(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);4jf.setDefaultCloseOperatio
5、n(JFrame.EXIT_ON_CLOSE);for(inti=0;i<20;i++){//注册监听jb[i].addActionListener(this);}}publicvoidactionPerformed(ActionEventae){Strings=ae.getActionCommand();if(s.trim().matches("^\d$")){//判断是输入的是否是数字if(append){//追加数字Stringss=jtf.getText().trim();jtf.setText(ss+s.trim());}else{//替换文本框原来的数字j
6、tf.setText(s.trim());append=true;}}elseif("+-/*".indexOf(s.trim())!=-1){//判断按的是否是四则运算符num1=jtf.getText();//将第一次输入的数存储起来operator=s.trim();//将输入的符号存储起来append=false;}elseif("=".equals(s.trim())){Stringnum2=jtf.getText();doubled1=Double.parseDouble(num1);doubled2=Double.parseDouble(num2);if(
7、"+".equals(operator)){//加法运算d1=d1+d2;}elseif("-".equals(operator)){//减法运算d1=d1-d2;}elseif("*".equals(operator)){//乘法运算d1=d1*d2;}elseif("/".equals(operator)){//除法运算d1=d1/d2;}jtf.setText(d1+"");//显示结果append=false;}elseif(".".equals(s.trim())){//判断小数点Stringtemp=jtf.getText()