swing 实现计算器

package tarena;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class TestComputer
implements ActionListener{
JTextField jtext=new JTextField();
private boolean append =false;
private String s1="0";//保留第一个数
private String operator="=";//保留第一个操作符

public void actionPerformed(ActionEvent ae) {
String comm = ae.getActionCommand();
//jtext.setText(comm);
if("0123456789".indexOf(comm)!=-1){
if(append){//追加  注意理解*******
String temp=jtext.getText();
jtext.setText(temp+comm);
}
else{
jtext.setText(comm);
append =true;
}
}
else if(".".equals(comm)){
String temp=jtext.getText();
if(temp.indexOf(".")==-1){
jtext.setText(temp+".");
append = true;
}
}
else if("+-*/".indexOf(comm)!=-1){
if(operator.equals("=")){
s1=jtext.getText();
operator=comm;
append =false;
}
else{
String s2=jtext.getText();
double d1= Double.parseDouble(s1);
double d2= Double.parseDouble(s2);
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;}
s1=d1+"";
operator=comm;
append =false;
}

}
else if("=".equals(comm)){
String s2=jtext.getText();
double d1= Double.parseDouble(s1);
double d2= Double.parseDouble(s2);
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;}

if(d1==(int)d1){jtext.setText((int)d1+"");}
else {jtext.setText(d1+"");}
operator=comm;
append=false;
}
else if("+/-".equals(comm)){
String temp=jtext.getText();
if(temp.startsWith("-")){
jtext.setText(temp.substring(1));
}
else if(!temp.equals("0")){
jtext.setText("-"+temp);
}
}
else if("CE".equals(comm)||"C".equals(comm)){
jtext.setText("0");
append=false;
}
else if("back".equals(comm)){
String temp=jtext.getText();
if(temp.length()==1){
jtext.setText("0");
}
else if(temp.length()>0){
jtext.setText(temp.substring(0, temp.length()-1));
}
//else{jtext.setText("0");}

}

}


public TestComputer(){
jtext.setEditable(false);
JFrame jf = new JFrame("计算器");
JPanel jp=new JPanel();
JButton[] jb = new JButton[20];
String [] s={"back","CE","C","+",
"7","8","9","-",
"4","5","6","*",
"1","2","3","/",
"0","+/-",".","="};
jf.add(jp);
jf.add(jtext,BorderLayout.NORTH);

jp.setLayout(new GridLayout(5,4));
for(int i=0;i<5;i++){
for(int j=0;j<4;j++){
jb[j+i*4]=new JButton(s[j+i*4]);
jp.add(jb[j+i*4]);
jb[j+i*4].addActionListener(this);
}

}
jf.pack();
jf.setResizable(false);
jf.setLocation(300,300);//
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}
public static void main(String[] args) {
TestComputer ren=new TestComputer();
}

}

你可能感兴趣的:(C++,c,swing,C#,J#)