import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTextField;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.EventObject;
public class Calculator extends JFrame implements ActionListener{
String[] keys={"7","8","9","/","4","5","6",
"*","1","2","3","-","0",".","=","+"};
//保存按钮上字符
JButton b[]=new JButton[keys.length];
//按钮数组
JButton clear;
JPanel p=new JPanel();//中间面板
JTextField t=new JTextField("0.0");
//文本框并设置初始值
GridLayout g=new GridLayout(4,4,4,4);
//四行四列,行和列的间距
int j=0;
int action;
double sum=0,num;int i=0;
Calculator(){
setBounds(100,100,300,200);
//设置位置和大小
p.setLayout(g);//股票代码面板的布局设置为网格布局
for( int i = 0; i b[i] = new JButton(keys[i]); b[i].addActionListener(this); p.add(b[i]); }//实例化按钮,并添加到按钮中 clear = new JButton("Clear"); clear.addActionListener(this); t.setHorizontalAlignment(JTextField.RIGHT); //设置文字显示方式为右对齐 add(t,"North"); add(p); add(clear,"South"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); pack(); setVisible(true); }public static void main(String[] args) { Calculator f=new Calculator(); public void actionPerformed(ActionEvent a) { JButton b=(JButton)a.getSource();//求事件的发生源 String s=b.getText();//求事件源上的文字 char c=s.charAt(0); num=Double.parseDouble(t.getText().trim()); if(c=='+'){ if(j==0)sum=num; else if(action ==1)sum+=num; else if(action ==2)sum-=num; else if(action ==3)sum*=num; else sum/=num; t.setText(sum+""); j++;i=0;action=1; else if(c=='-'){ if(j==0)sum=num; else if(action ==1)sum+=num; else if(action ==2)sum-=num; else if(action ==3)sum*=num; else sum/=num; t.setText(sum+""); j++;i=0;action=2; else if(c=='*'){ if(j==0)sum=num; else if(action ==1)sum+=num; else if(action ==2)sum-=num; else if(action ==3)sum*=num; else sum/=num; t.setText(sum+""); j++;i=0;action=3; else if(c=='/'){ if(j==0)sum=num; else if(action ==1)sum+=num; else if(action ==2)sum-=num; else if(action ==3)sum*=num; else sum/=num; t.setText(sum+""); j++;i=0;action=4; else if(c=='='){ switch(action){ case 1 :t.setText((sum+=num)+"");break; case 2 :t.setText((sum-=num)+"");break case 3 :t.setText((sum*=num)+"");break; case 4 :t.setText((sum/=num)+"");break; } t.setText(sum+""); j++;i=0;action=0; else if(c=='.'){ if(t.getText().indexOf('.')==-1) t.setText(t.getText()+c); else if(c=='C'){//复位 i=0;j=0;sum=0;action=0; t.setText("0.0");else {if(i==0) t.setText(""); t.setText(t.getText()+c); i++;