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转换成字符串str t.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(); }}