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();
}
}