Java Swing做的简易计算器

先整了一个包

package cn.cal;

包里面有两个类:

一个 Calculator extends JFrame 实现计算器的界面

一个 Calculate 实现对算术表达式的处理

Calculator extends JFrame代码:

PS:除了各个按钮的监听事件是自己写的,其他部分当然都是用的WindowBuilder插件拖拉完成=-=

package cn.cal;

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.Font;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.JTextArea;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class Calculator extends JFrame {

	private JPanel contentPane;
	private String s = "";
	//因为按了"="之后按任意键后默认清屏,所以设置start标记是否需要清屏
	boolean start = false;
	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					Calculator frame = new Calculator();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public Calculator() {
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 346, 478);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		JTextArea in = new JTextArea();
		JButton btnC = new JButton("1");
		btnC.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (start){
					s = "";
					start = false;
				}
				s+="1";
				in.setText(s);
			}
		});
		btnC.setFont(new Font("宋体", Font.PLAIN, 22));
		
		JButton btnD = new JButton("2");
		btnD.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (start){
					s = "";
					start = false;
				}
				s+="2";
				in.setText(s);
			}
		});
		btnD.setFont(new Font("宋体", Font.PLAIN, 22));
		
		JButton button = new JButton("3");
		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (start){
					s = "";
					start = false;
				}
				s+="3";
				in.setText(s);
			}
		});
		button.setFont(new Font("宋体", Font.PLAIN, 22));
		
		JButton button_1 = new JButton("4");
		button_1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (start){
					s = "";
					start = false;
				}
				s+="4";
				in.setText(s);
			}
		});
		button_1.setFont(new Font("宋体", Font.PLAIN, 22));
		
		JButton button_2 = new JButton("5");
		button_2.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (start){
					s = "";
					start = false;
				}
				s+="5";
				in.setText(s);
			}
		});
		button_2.setFont(new Font("宋体", Font.PLAIN, 22));
		
		JButton button_3 = new JButton("6");
		button_3.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (start){
					s = "";
					start = false;
				}
				s+="6";
				in.setText(s);
			}
		});
		button_3.setFont(new Font("宋体", Font.PLAIN, 22));
		
		JButton button_4 = new JButton("7");
		button_4.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (start){
					s = "";
					start = false;
				}
				s+="7";
				in.setText(s);
			}
		});
		button_4.setFont(new Font("宋体", Font.PLAIN, 22));
		
		JButton button_5 = new JButton("8");
		button_5.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (start){
					s = "";
					start = false;
				}
				s+="8";
				in.setText(s);
			}
		});
		button_5.setFont(new Font("宋体", Font.PLAIN, 22));
		
		JButton button_6 = new JButton("9");
		button_6.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (start){
					s = "";
					start = false;
				}
				s+="9";
				in.setText(s);
			}
		});
		button_6.setFont(new Font("宋体", Font.PLAIN, 22));
		
		JButton button_7 = new JButton("+");
		button_7.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (start){
					s = "";
					start = false;
				}
				s+="+";
				in.setText(s);
			}
		});
		button_7.setFont(new Font("宋体", Font.PLAIN, 22));
		
		JButton button_8 = new JButton("-");
		button_8.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (start){
					s = "";
					start = false;
				}
				s+="-";
				in.setText(s);
			}
		});
		button_8.setFont(new Font("宋体", Font.PLAIN, 22));
		
		JButton button_9 = new JButton("*");
		button_9.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (start){
					s = "";
					start = false;
				}
				s+="*";
				in.setText(s);
			}
		});
		button_9.setFont(new Font("宋体", Font.PLAIN, 22));
		
		JButton button_10 = new JButton("/");
		button_10.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (start){
					s = "";
					start = false;
				}
				s+="/";
				in.setText(s);
			}
		});
		button_10.setFont(new Font("宋体", Font.PLAIN, 22));
		
		JButton btnC_2 = new JButton("C");//清屏
		btnC_2.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (start){
					s = "";
					start = false;
				}
				s = "";
				in.setText(s);
			}
		});
		btnC_2.setFont(new Font("宋体", Font.PLAIN, 22));
		
		JButton button_12 = new JButton("(");
		button_12.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (start){
					s = "";
					start = false;
				}
				s+="(";
				in.setText(s);
			}
		});
		button_12.setFont(new Font("宋体", Font.PLAIN, 22));
		
		JButton button_13 = new JButton(")");
		button_13.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (start){
					s = "";
					start = false;
				}
				s+=")";
				in.setText(s);
			}
		});
		button_13.setFont(new Font("宋体", Font.PLAIN, 22));
		
		JButton btnC_1 = new JButton(".");
		btnC_1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (start){
					s = "";
					start = false;
				}
				s+=".";
				in.setText(s);
			}
		});
		btnC_1.setFont(new Font("宋体", Font.PLAIN, 22));
		
		JButton button_14 = new JButton("0");
		button_14.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (start){
					s = "";
					start = false;
				}
				s+="0";
				in.setText(s);
			}
		});
		button_14.setFont(new Font("宋体", Font.PLAIN, 22));
		
		JButton btnD_1 = new JButton("D");//删除
		btnD_1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (start){
					s = "";
					start = false;
				}
				if (s.length()>0){
					s = s.substring(0, s.length()-1);
				}
				in.setText(s);
			}
		});
		btnD_1.setFont(new Font("宋体", Font.PLAIN, 22));
		
		JButton button_11 = new JButton("=");
		button_11.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				Calculate ans = new Calculate();
				in.setText(s+"\n"+ans.EvaluateExpression(s+'#'));
				start = true;
			}
		});
		button_11.setFont(new Font("宋体", Font.PLAIN, 22));
		
		
		in.setFont(new Font("Consolas", Font.PLAIN, 20));
		GroupLayout gl_contentPane = new GroupLayout(contentPane);
		gl_contentPane.setHorizontalGroup(
			gl_contentPane.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_contentPane.createSequentialGroup()
					.addGap(28)
					.addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING, false)
						.addGroup(gl_contentPane.createSequentialGroup()
							.addComponent(btnC_1, GroupLayout.PREFERRED_SIZE, 52, GroupLayout.PREFERRED_SIZE)
							.addGap(18)
							.addComponent(btnC_2, GroupLayout.PREFERRED_SIZE, 52, GroupLayout.PREFERRED_SIZE)
							.addPreferredGap(ComponentPlacement.UNRELATED)
							.addComponent(btnD_1, GroupLayout.PREFERRED_SIZE, 52, GroupLayout.PREFERRED_SIZE)
							.addGap(18)
							.addComponent(button_11, GroupLayout.PREFERRED_SIZE, 52, GroupLayout.PREFERRED_SIZE))
						.addGroup(gl_contentPane.createSequentialGroup()
							.addComponent(button_10, GroupLayout.PREFERRED_SIZE, 52, GroupLayout.PREFERRED_SIZE)
							.addGap(18)
							.addComponent(button_14, GroupLayout.PREFERRED_SIZE, 52, GroupLayout.PREFERRED_SIZE)
							.addPreferredGap(ComponentPlacement.UNRELATED)
							.addComponent(button_12, GroupLayout.PREFERRED_SIZE, 52, GroupLayout.PREFERRED_SIZE)
							.addGap(18)
							.addComponent(button_13, GroupLayout.PREFERRED_SIZE, 52, GroupLayout.PREFERRED_SIZE))
						.addGroup(gl_contentPane.createSequentialGroup()
							.addComponent(button_4, GroupLayout.PREFERRED_SIZE, 52, GroupLayout.PREFERRED_SIZE)
							.addGap(18)
							.addComponent(button_5, GroupLayout.PREFERRED_SIZE, 52, GroupLayout.PREFERRED_SIZE)
							.addGap(15)
							.addComponent(button_6, GroupLayout.PREFERRED_SIZE, 52, GroupLayout.PREFERRED_SIZE)
							.addGap(18)
							.addComponent(button_9, GroupLayout.PREFERRED_SIZE, 52, GroupLayout.PREFERRED_SIZE))
						.addGroup(gl_contentPane.createSequentialGroup()
							.addComponent(button_1, GroupLayout.PREFERRED_SIZE, 52, GroupLayout.PREFERRED_SIZE)
							.addGap(18)
							.addComponent(button_2, GroupLayout.PREFERRED_SIZE, 52, GroupLayout.PREFERRED_SIZE)
							.addPreferredGap(ComponentPlacement.UNRELATED)
							.addComponent(button_3, GroupLayout.PREFERRED_SIZE, 52, GroupLayout.PREFERRED_SIZE)
							.addGap(18)
							.addComponent(button_8, GroupLayout.PREFERRED_SIZE, 52, GroupLayout.PREFERRED_SIZE))
						.addGroup(gl_contentPane.createSequentialGroup()
							.addComponent(btnC, GroupLayout.PREFERRED_SIZE, 52, GroupLayout.PREFERRED_SIZE)
							.addGap(18)
							.addComponent(btnD, GroupLayout.PREFERRED_SIZE, 52, GroupLayout.PREFERRED_SIZE)
							.addPreferredGap(ComponentPlacement.UNRELATED)
							.addComponent(button, GroupLayout.PREFERRED_SIZE, 52, GroupLayout.PREFERRED_SIZE)
							.addGap(18)
							.addComponent(button_7, GroupLayout.PREFERRED_SIZE, 52, GroupLayout.PREFERRED_SIZE))
						.addComponent(in))
					.addContainerGap(27, Short.MAX_VALUE))
		);
		gl_contentPane.setVerticalGroup(
			gl_contentPane.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_contentPane.createSequentialGroup()
					.addGap(38)
					.addComponent(in, GroupLayout.PREFERRED_SIZE, 51, GroupLayout.PREFERRED_SIZE)
					.addGap(18)
					.addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING)
						.addComponent(btnC, GroupLayout.PREFERRED_SIZE, 40, GroupLayout.PREFERRED_SIZE)
						.addComponent(btnD, GroupLayout.PREFERRED_SIZE, 40, GroupLayout.PREFERRED_SIZE)
						.addComponent(button, GroupLayout.PREFERRED_SIZE, 40, GroupLayout.PREFERRED_SIZE)
						.addComponent(button_7, GroupLayout.PREFERRED_SIZE, 40, GroupLayout.PREFERRED_SIZE))
					.addGap(18)
					.addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING)
						.addComponent(button_1, GroupLayout.PREFERRED_SIZE, 40, GroupLayout.PREFERRED_SIZE)
						.addComponent(button_2, GroupLayout.PREFERRED_SIZE, 40, GroupLayout.PREFERRED_SIZE)
						.addComponent(button_3, GroupLayout.PREFERRED_SIZE, 40, GroupLayout.PREFERRED_SIZE)
						.addComponent(button_8, GroupLayout.PREFERRED_SIZE, 40, GroupLayout.PREFERRED_SIZE))
					.addPreferredGap(ComponentPlacement.UNRELATED)
					.addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING)
						.addComponent(button_4, GroupLayout.PREFERRED_SIZE, 40, GroupLayout.PREFERRED_SIZE)
						.addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE)
							.addComponent(button_5, GroupLayout.PREFERRED_SIZE, 40, GroupLayout.PREFERRED_SIZE)
							.addComponent(button_6, GroupLayout.PREFERRED_SIZE, 40, GroupLayout.PREFERRED_SIZE))
						.addComponent(button_9, GroupLayout.PREFERRED_SIZE, 40, GroupLayout.PREFERRED_SIZE))
					.addGap(18)
					.addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING)
						.addComponent(button_10, GroupLayout.PREFERRED_SIZE, 40, GroupLayout.PREFERRED_SIZE)
						.addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE)
							.addComponent(button_14, GroupLayout.PREFERRED_SIZE, 40, GroupLayout.PREFERRED_SIZE)
							.addComponent(button_12, GroupLayout.PREFERRED_SIZE, 40, GroupLayout.PREFERRED_SIZE)
							.addComponent(button_13, GroupLayout.PREFERRED_SIZE, 40, GroupLayout.PREFERRED_SIZE)))
					.addPreferredGap(ComponentPlacement.UNRELATED)
					.addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING)
						.addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE)
							.addComponent(btnC_1, GroupLayout.PREFERRED_SIZE, 40, GroupLayout.PREFERRED_SIZE)
							.addComponent(btnC_2, GroupLayout.PREFERRED_SIZE, 40, GroupLayout.PREFERRED_SIZE))
						.addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE)
							.addComponent(btnD_1, GroupLayout.PREFERRED_SIZE, 40, GroupLayout.PREFERRED_SIZE)
							.addComponent(button_11, GroupLayout.PREFERRED_SIZE, 40, GroupLayout.PREFERRED_SIZE)))
					.addContainerGap(39, Short.MAX_VALUE))
		);
		contentPane.setLayout(gl_contentPane);
	}
}


Calculate代码:

package cn.cal;

import java.util.Scanner;

/**
 * 栈实现对算术表达式的处理
 * 对in进行处理,求出结果转化为字符串返回
 * 若算是表达式错误返回"ERROR!"
 * @author Must_so
 */
public class Calculate {
	/**
	 * 数组模拟栈
	 * 数组模拟集合
	 */
	double[] opnd;//操作数栈
	int p = -1;//空栈
	String optr;//操作符栈
	final String op ="+-*/()#";//op是运算符集合
	void InitStack(){
		p = -1;
		opnd = new double[100];
		optr = "";
	}
	int count(char c){
		int t = 0;
		for (int i = 0;i < op.length();++i){
			if (c == op.charAt(i)) t++;
		}
		return t;
	}
	char Precede(char c1,char c2){
		if (c1 == '+'||c1 == '-'){
	        if (c2 == '+'||c2 == '-'||c2 == ')'||c2=='#') return '>';
	        else return '<';
	    }
	    if (c1 == '*'||c1 == '/'){
	        if (c2 == '(') return '<';
	        else return '>';
	    }
	    if (c1 == '('){
	        if (c2 == ')') return '=';
	        if (c2 == '#') return '!';//不合法的算术表达式
	        return '<';
	    }
	    if (c1 == ')'){
	        if (c2=='(') return '!';
	        return '>';
	    }
	    if (c1 == '#'){
	        if (c2 == '#') return '=';
	        if (c2 == ')') return '!';
	        return '<';
	    }
	    return '!';
	}
	double turnToDouble(String s){
		//字符串转化成浮点型数
		return Double.parseDouble(s);
	}
	String turnToString(double d){
		//浮点型转化成字符串
		return Double.toString(d);
	}
	double Operate(double a,char c,double b){
	    if (c=='+') return a+b;
	    if (c=='-') return a-b;
	    if (c=='*') return a*b;
	    if (c=='/') return a/b;
		return 0.0;
	}
	String EvaluateExpression(String s){
		InitStack();
		optr = "#";
		int i = 0;
		boolean ERROR = false;
		while (s.charAt(i)!='#'||optr.charAt(optr.length()-1)!='#'){
				String tmp = "";
				while (i < s.length()&&count(s.charAt(i))==0){
					tmp+=s.charAt(i++);
				}
				if (!tmp.equals("")){
					//不是操作符而是操作数
					opnd[++p] = turnToDouble(tmp);
				}else {
					switch(Precede(optr.charAt(optr.length()-1),s.charAt(i))){
					case '!':
						ERROR = true;
						break;
					case '<'://栈顶元素优先级低
						optr+=s.charAt(i++);
						break;
					case '='://脱括号并接收下一个字符
						optr = optr.substring(0, optr.length()-1);
						++i;
						break;
					case '>'://退栈并将运算结果入栈
						char theta = optr.charAt(optr.length()-1);
						optr = optr.substring(0, optr.length()-1);
						double b = opnd[p--];
						double a = opnd[p--];
						if (theta == '/'&&b==0.0){
							return "ERROR!";//除零
						}
						opnd[++p] = Operate(a,theta,b);
						break;
					}//switch 
				}
				if (ERROR) return "ERROR!";
		}//while
		return turnToString(opnd[p]);
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String s;
		Scanner in = new Scanner(System.in);
		Calculate ans = new Calculate(); 
		while (in.hasNext()){
			s = in.next();
			System.out.println(ans.EvaluateExpression(s));
		}
	}
}

运行结果:



  • 3
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值