简易calc

1.简易计算的实现


package action;


import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;


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


public class Calc extends JFrame{



JPanel pnlContent,pnlUp,pnlDown,pnlLeft,pnlRight;
JTextField txtRes;

String[] numAndOp={
"1","2","3","+",
"4","5","6","-",
"7","8","9","*",
"0","C","=","/",
};


boolean inNew=false;  //是否是新操作数
String  oldOp=""; //保存上一个操作符
double total=0; //保存总结果



public Calc() {
this.setTitle("简易计算器");

pnlContent=new JPanel(new BorderLayout());
pnlUp=new JPanel(new FlowLayout());
pnlDown=new JPanel(new GridLayout(4,4,22,22));
pnlLeft=new JPanel();
pnlRight=new JPanel();


txtRes=new JTextField(21);
txtRes.setEditable(false);
txtRes.setText("0");
txtRes.setHorizontalAlignment(JTextField.RIGHT);
// txtRes.setBorder(BorderFactory.createLineBorder(Color.BLACK));


pnlUp.add(txtRes);

this.setContentPane(pnlContent);

pnlContent.add(pnlUp,BorderLayout.NORTH);
pnlContent.add(pnlDown);
pnlContent.add(pnlLeft,BorderLayout.WEST);
pnlContent.add(pnlRight,BorderLayout.EAST);


for(String s:numAndOp){
JButton btn=new JButton(s);
pnlDown.add(btn);

btn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {

String btnTxt=e.getActionCommand();

String  ops="+-*/=";

if(btnTxt.equals("C")){ //清除按钮
clearAll();
}else if(ops.indexOf(btnTxt)!=-1){ //操作符按钮
enterOp(btnTxt);
}else {  //数字按钮
enterNum(btnTxt);
}
}
});
}




this.setSize(260, 270);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setResizable(false);
this.setVisible(true);

}


//按下数字处理方法
public void enterNum(String num){
if(inNew){   //是否是新操作数
txtRes.setText(num);  
inNew=false;
}else{
if(txtRes.getText().equals("0")){ 
txtRes.setText(num);
}else{
txtRes.setText(txtRes.getText()+num);
}
}
}

//按下操作符处理方法
public void enterOp(String op){

inNew=true;

double num=Double.valueOf(txtRes.getText());
//进行上一次的运算
if(oldOp.equals("+")){
total+=num;
}else if(oldOp.equals("-")){
total-=num;
}else if(oldOp.equals("*")){
total*=num;
}else if(oldOp.equals("/")){
total/=num;
}else{
total=num;
}
oldOp=op; //保存操作符


txtRes.setText(total+"");
}

//按下清除键处理方法
public void clearAll(){



txtRes.setText("0");
inNew=false;  //是否是新操作数
oldOp=""; //保存上一个操作符
total=0; //保存总结果

}

public static void main(String[] args) {
new Calc();
}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值