楼主 不厚道,一句注释也没有!!
我不是很清楚你的标志位都是做什么用的,自己跟着感觉给你改了一个填了一个! 凑合着看吧,应该能看懂- import java.awt.*;
- import javax.swing.*;
- import java.awt.event.*;
- class CalButtonPane extends JPanel implements ActionListener{
- String[] keys={"7","8","9","/",
- "4","5","6","*",
- "1","2","3","-",
- "0",".","=","+"};
- JButton[] keyb=new JButton[keys.length];
- JTextField t;
- JButton clear;
- double result=0,num,sum;
- int i=1,j=0,action,k=0;//i j 为标记符i=1表示按下了计算按钮,文本框要置0,
- CalButtonPane(JTextField t,JButton clear){
- super(new GridLayout(4,4,4,4));
- this.t=t;
- this.clear=clear;
- for(int i=0;i<keys.length;i++)
- {
- keyb[i]=new JButton(keys[i]);
- keyb[i].addActionListener(this);
- this.add(keyb[i]);
- }
- clear.addActionListener(this);
- }
- public void actionPerformed(ActionEvent e){
- JButton o=(JButton)e.getSource();
- String s=o.getText();
- char c=s.charAt(0);
- num=Double.parseDouble(t.getText());
- if(c=='+')
- {
- if(j==0)sum=num;
- else if(action==1)sum+=num;
- t.setText(sum+"");
- j++;i=0;action=1;
- }
- else if(c=='-'){
- if(j==0)sum=num;
- else if(action==2)sum-=num;
- t.setText(sum+"");
- j++;i=0;action=2;
- }
- else if(c=='*'){
- if(j==0)sum=num;
- else if(action==3)sum*=num;
- t.setText(sum+"");
- j++;i=0;action=3;
- }
- else if(c=='/'){
- if(j==0)sum=num;
- else if(action==4)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+"");
- // i=1;j=0;action=0; 按下等号后 让标志位i置零,表示一次计算结束
- i=0;j=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");
- }
- else
- {
- System.out.println(i);
-
- if(i==0 || k==0)t.setText("");//若 标志位 k=0 表示输入第一个数字, 因为 默认显示 0.0 不判断 会直接加在后面
- i=1;k=1;
- t.setText(t.getText()+c);
- }
- }
- }
- public class Calculator extends JFrame{
- CalButtonPane cp;
- Calculator() {
- super("java计算器");
- setDefaultCloseOperation(EXIT_ON_CLOSE);
- init();
- Container c=getContentPane();
- c.setLayout(new BorderLayout());
- c.add(cp,"Center");
- c.add(cp.t,"North");
- c.add(cp.clear,"South");
- this.setLocation(300,200);
- this.pack();
- this.setResizable(false );
- this.setVisible(true);
-
- }
- void init(){
- JTextField t=new JTextField("0.0");
- t.setHorizontalAlignment(JTextField.RIGHT);//设置文本的水平对齐方式。
-
- JButton clear=new JButton("Clear");
- cp=new CalButtonPane(t,clear);
- }
-
- public static void main(String[] args) {
- new Calculator();
- }
- }
复制代码 |