package home;
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 Clculator implements ActionListener{
JTextField jtf=new JTextField(20);
private boolean append=false;//默认是替换状态 标记
private String s1="0";//保留第一个操作数
private String operator="+";//保留运算符
@Override
public void actionPerformed(ActionEvent ae) {
String comm=ae.getActionCommand();
//jtf.setText(comm);
if("0123456789".indexOf(comm)!=-1){
if(append){//追加分支
String temp=jtf.getText();
jtf.setText(temp+comm);
}else{//替换分支
jtf.setText(comm);
append=true;
}
}else if(".".equals(comm)){
String temp=jtf.getText();
if(temp.indexOf(".")==-1){//不存在
jtf.setText(temp+".");
append=true;
}
}else if("+-*/".indexOf(comm)!=-1){
s1=jtf.getText();
operator=comm;
append=false;
}else if("=".equals(comm)){
String s2=jtf.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){
jtf.setText((int)d1+"");
}else{
jtf.setText(""+d1);
}
append=false;
}else if("+/-".equals(comm)){
String temp=jtf.getText();
if(temp.startsWith("-")){
jtf.setText(temp.substring(1));
}else if(!temp.equals("0")){
jtf.setText("-"+temp);
}
}else if("CE".equals(comm)|| "C".equals(comm)){
jtf.setText("0");
append=false;
}else if("Back".equals(comm)){
String temp=jtf.getText();
if(temp.length()>0){
jtf.setText(temp.substring(0,temp.length()-1));
}
}
}
public Clculator(){
JFrame jf=new JFrame("计算器 v6.0 ");
jf.add(jtf,BorderLayout.NORTH);
JPanel jp=new JPanel();
jp.setLayout(new GridLayout(5,4));
String[] lable1={"Back","CE","C","+",
"7","8","9","-",
"4","5","6","*",
"1","2","3","4",
"0","+/-",".","="};
JButton[] jb=new JButton[lable1.length];
for(int i=0;i<jb.length;i++){
jb[i] =new JButton(lable1[i]);
jp.add(jb[i],BorderLayout.CENTER);
jb[i].addActionListener(this);
}
jf.add(jp);
jf.pack();//自动调整大小
//jf.setSize(300,200);
jf.setLocation(600, 500);
jf.setVisible(true);//尽可能往后放
jf.setResizable(false);//窗口大小固定
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
Clculator cl=new Clculator();
}
}
/*计算器界面制作步骤:
* 1、将文本框加入到窗口中;
* 2、将按钮加入到面板中;
* 3、将面板加入到窗口中。
*/