Java课设案例之百行代码实现简易计算器
package start;
import javax.swing.*;
import util.Const;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class calculator extends JFrame implements ActionListener{
/**********************北面的控件***********************/
private JPanel jp_north = new JPanel();
private JTextField input_text = new JTextField();
private JButton c_Btn = new JButton("Clear");
/**********************中间的控件***********************/
private JPanel jp_center = new JPanel();
public calculator() throws HeadlessException{//显示窗体
this.init();
this.addNorthComponent();
this.addCenterButton();
}
//初始化的方法
public void init(){
this.setTitle(Const.TITLE);
this.setSize(Const.FRAME_W, Const.FRAME_H);
this.setLayout(new BorderLayout());
this.setResizable(false);
this.setLocation(Const.Frame_X,Const.Frame_Y);//设置框架在屏幕的位置
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//设置关闭键
}
//添加北面的控件
public void addNorthComponent(){
this.input_text.setPreferredSize(new Dimension(200,30));//设置文本框大小
jp_north.add(input_text);//加文本框
this.c_Btn.setForeground(Color.RED);//设置按钮颜色
jp_north.add(c_Btn);//加按钮
c_Btn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
input_text.setText("");
}
});
this.add(jp_north,BorderLayout.NORTH);//将面板加到框架北侧
}
//添加中间按钮
public void addCenterButton(){
String btn_text = "123+456-789*0.=/";
String regex = "[+-*/.=]";//正则表达式
this.jp_center.setLayout(new GridLayout(4,4));//4*4的布局
for(int i=0;i<16;i++){//在面板中加按钮
String tmp = btn_text.substring(i,i+1);
JButton btn = new JButton();
btn.setText(tmp);//给按钮加文字
if(tmp.matches(regex)){//如果正则匹配
btn.setFont(new Font("粗体",Font.BOLD,20));
btn.setForeground(Color.RED);
}
btn.addActionListener(this);//添加按钮监听器
jp_center.add(btn);
}
this.add(jp_center,BorderLayout.CENTER);//将面板加载框架布局的中间位置
}
private String firstInput = null;
private String operator = null;
//给按钮添加监听事件
public void actionPerformed(ActionEvent e){
String clickStr = e.getActionCommand();
if(".0123456789".indexOf(clickStr)!=-1){//数字输入
this.input_text.setText(input_text.getText() + clickStr);
this.input_text.setHorizontalAlignment(JTextField.RIGHT);
}
else if(clickStr.matches("[+-*/]{1}")){//运算符输入
operator = clickStr;
firstInput = this.input_text.getText();
this.input_text.setText("");
}
else if(clickStr.equals("=")){//等号输入
Double a = Double.valueOf(firstInput);
Double b = Double.valueOf(this.input_text.getText());
Double res = null;
switch (operator){//运算主体
case "+":
res = a + b;
break;
case "-":
res = a - b;
break;
case "*":
res = a * b;
break;
case "/":
if(b!=0){
res = a/b;
}
else{
this.input_text.setText("除数不能为0!请清空!");
}
break;
}
this.input_text.setText(res.toString());
}
}
//主方法
public static void main(String[] args) {
calculator Calculator = new calculator();
Calculator.setVisible(true);
}
}