Java 用swing实现简单计算器

前言

我第一次写文章,就摸索了一会儿这个编辑器,排版可能不会太好,请见谅。主要还是上课时做了一个这个作业,个人感觉还行就分享给大家了。当然做得比我好的多了去了,我做的功能不是很多,可能还有遗留的bug,大家一起完善吧!

先看看运行的样子吧

Java 用swing实现简单计算器_第1张图片
色调借鉴了win10自带的计算器(我觉得挺好看的)

还是直接上代码吧

代码

感觉写得有点长,主要是为了完善功能,比如混合运算等一些细节上的问题,不知道大家有没有更好的方法。

package chap01;

import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;

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

public class Calculator extends JFrame implements ActionListener{
	private JTextField result = new JTextField("0");//结果显示
	private String[] button={" ","Backspace","CE","C","MC","7","8","9","/","sqrt","MR","4","5","6","*","%","M-","1","2","3","-","1/x","M+","0","+/-",".","+","="};
	private JButton Button[] = new JButton[button.length];//按钮组件
	private String c="";//记录当前计算符号( + - * /)
	private char[] str = new char[15];//记录输入数字
	private int x=0,y=0,flag=0;//x 数字字符数组下标,y字符串数组下标,flag 判断小数点
	private String[] number = new String[100];//存取计算数字字符串
	private double n1=0,n2=0;//运算参数
	private String M1="0",M2="0";//内存运算参数
	private int mr=0,mc=0;//记录MR、MC按钮在数组里的下标
	private JTextField M = new JTextField();
	private JTextField MM = new JTextField();
	public Calculator(){
		super("拉垮的计算器");
		Design();
	}
	//界面设计
	public void Design() {
		setSize(820,485);
		setLocationRelativeTo(null);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		setLayout(null);//绝对分布
		setBackground(new Color(202,202,202));//设置背景颜色
		result.setBounds(5, 0, 625, 70);
		result.setHorizontalAlignment(JTextField.RIGHT);//文本输出靠右
		result.setEditable(false);//不可键盘编辑
		result.setFont(new Font("黑体",Font.PLAIN,50));//设置文本字体
		result.setBorder(null);//边框透明
		add(result);//加入组件
		int x=5,y=75;
		for(int i=0;i<button.length;i++) {
			Button[i] = new JButton();
			Button[i].setText(button[i]);//按钮文本
			Button[i].setFont(new Font("黑体",Font.PLAIN,26));//设置组件字体
			Button[i].setFocusPainted(false);//设置不绘制焦点
			Button[i].setBorderPainted(false);//设置按钮边框透明
			if(y==75&&x>5) {
				Button[i].setBounds(x,y,170,70);
				Button[i].setBackground(new Color(225,225,225));//设置按钮颜色
				x+=175;
				if(x>525) {
					x=5;
					y+=75;
				}
			}
			else{
				Button[i].setBounds(x,y,100,70);
				if(button[i]==" "||button[i]=="MC"||button[i]=="MR"||button[i]=="M-"||button[i]=="M+"||button[i]=="/"||button[i]=="*"||button[i]=="-"||button[i]=="+"||button[i]=="sqrt"||button[i]=="%"||button[i]=="1/x") {
					Button[i].setBackground(new Color(225,225,225));
					if(button[i] == "MR") {
						mr = i;
						Button[i].setEnabled(false);
					}
					if(button[i] == "MC") {
						mc = i;
						Button[i].setEnabled(false);
					}
				}
				else if(button[i]=="=") {
					Button[i].setBackground(new Color(122,170,208));
				}
				else{
					Button[i].setBackground(new Color(245,245,245));
				}
				if(x<525) {
					x+=105;
				}
				else {
					x=5;
					y+=75;
				}
			}
			add(Button[i]);
		}
		for(int i=0;i<button.length;i++) {
			Button[i].addActionListener(this);//添加事件
		}
		MM.setBounds(635, 20, 185, 50);
		MM.setHorizontalAlignment(JTextField.LEFT);
		MM.setEditable(false);
		MM.setText("内存:");
		MM.setFont(new Font("黑体",Font.PLAIN,26));
		MM.setBorder(null);
		add(MM);
		M.setBounds(635, 100, 185, 275);
		M.setHorizontalAlignment(JTextField.CENTER);
		M.setEditable(false);
		M.setFont(new Font("黑体",Font.PLAIN,24));
		M.setBorder(null);
		add(M);
		number[0]="0";
		setResizable(false);//窗口用户不可放大
		setVisible(true);
	}
	@Override
	public void actionPerformed(ActionEvent e) {
		// TODO 自动生成的方法存根
		String s = e.getActionCommand();
		if(s=="sqrt"||s=="1/x") {
			x=0;
		}
		else if(s=="+"||s=="-"||s=="*"||s=="/") {//加减乘除运算判断
			if(y>1) {
				Result();
			}
			c=s;
			x=0;
			System.out.println(number[y]);
			if(number[y]==null) {//用于更改当前已选择运算符号时,保持y不变
				y--;
			}
			y++;
			System.out.println(number[y]);
			flag=0;
		}
		else {
			getnum(s);
		}
		switch(s){
			case " ":
				result.setText("后备隐藏能源!");//瞎搞
				break;
			case "C":
				c = "0";
				for(int i=0;i<number.length;i++) {//初始化
					number[i] = null;
				}
				number[0]="0";
				x=0;
				y=0;
				flag=0;
				result.setText(c);
				break;
			case "sqrt":
				double a1;
				if(number[y]==null) {
					a1 = Double.valueOf(number[y-1]);//String 转 double
				}
				else {
					a1 = Double.valueOf(number[y]);
				}
				if(a1<0) {
					result.setText("无效输入");
				}
				else {
					a1 = Math.sqrt(a1);
					result.setText(Judge(a1));
					number[y] = String.valueOf(a1);
				}
				break;
			case "%":
				switch(c) {
					case "+":
						n1 = Double.valueOf(number[y-1]);
						n2 = Double.valueOf(number[y]);
						n2 = n1*n2/100;
						result.setText(Judge(n2));
						number[y] = String.valueOf(n2);
						break;
					case "-":
						n1 = Double.valueOf(number[y-1]);
						n2 = Double.valueOf(number[y]);
						n2 = n1*n2/100;
						result.setText(Judge(n2));
						number[y] = String.valueOf(n2);
						break;
					case "*":
						n2 = Double.valueOf(number[y]);
						n2 = n2/100;
						result.setText(Judge(n2));
						number[y] = String.valueOf(n2);
						break;
					case "/":
						n2 = Double.valueOf(number[y]);
						n2 = n2/100;
						result.setText(Judge(n2));
						number[y] = String.valueOf(n2);
						break;
				}
				break;
			case "+/-":
				double a4 = Double.valueOf(number[y]);
				a4=-a4;
				if(a4<0) {
					for(int i=str.length-1;i>0;i--) {
						str[i]=str[i-1];
					}
					str[0]='-';
					x++;
				}
				else if(a4>0){
					for(int i=0;i<str.length-1;i++) {
						str[i]=str[i+1];
					}
					x--;
				}
				else {
					a4 = 0;//a4会出现值为-0.0的情况,所以再次使a4=0
				}
				result.setText(Judge(a4));
				number[y] = String.valueOf(a4);
				break;
			case "1/x":
				double a5;
				if(number[y]==null) {
					a5 = Double.valueOf(number[y-1]);//String 转 double
				}
				else {
					a5 = Double.valueOf(number[y]);
				}
				if(a5 == 0) {
					result.setText("除数不能为零");
				}
				else {
					a5=1/a5;
					number[y] = String.valueOf(a5);
					result.setText(Judge(a5));
				}
				break;
			case "CE":
				number[y]="0";
				result.setText(number[y]);
				x=0;
				break;
			case "Backspace":
				if(x==0) {
					result.setText("0");
				}
				else if(x==1) {
					x--;
					str[x]='0';
					number[y] = String.valueOf(str,0,x+1);
					result.setText(number[y]);
				}
				else if(x==2 && Double.valueOf(number[y])<0) {//这里是负数退格的情况处理
					x=0;
					str[x]='0';
					number[y] = String.valueOf(str,0,x+1);
					result.setText(number[y]);
				}
				else {
					x--;
					number[y] = String.valueOf(str,0,x);
					result.setText(number[y]);
				}
				break;
			
			case "=":
				Result();
				number[0] = number[y];
				for(int i=1;i<number.length;i++) {
					number[i] = null;
				}
				c = "0";
				x=0;
				y=0;
				break;
			case "M+":
				Memory("M+");
				Button[mr].setEnabled(true);
				Button[mc].setEnabled(true);
				break;
			case "M-":
				Memory("M-");
				Button[mr].setEnabled(true);
				Button[mc].setEnabled(true);
				break;
			case "MR":
				result.setText(M1);//显示内存数值
				break;
			case "MC":
				M1="0";
				M2="0";
				Button[mr].setEnabled(false);
				Button[mc].setEnabled(false);
				M.setText("");//清空内存
				break;
		}
	}
	//输入计算的数字
	public void getnum(String cc) {
		switch(cc) {
		case "0":
			str[x]='0';
			number[y] = String.valueOf(str,0,x+1);
			result.setText(number[y]);
			x++;
			break;
		case "1":
			str[x]='1';
			number[y] = String.valueOf(str,0,x+1);
			result.setText(number[y]);
			x++;
			break;
		case "2":
			str[x]='2';
			number[y] = String.valueOf(str,0,x+1);
			result.setText(number[y]);
			x++;
			break;
		case "3":
			str[x]='3';
			number[y] = String.valueOf(str,0,x+1);
			result.setText(number[y]);
			x++;
			break;
		case "4":
			str[x]='4';
			number[y] = String.valueOf(str,0,x+1);
			result.setText(number[y]);
			x++;
			break;
		case "5":
			str[x]='5';
			number[y] = String.valueOf(str,0,x+1);
			result.setText(number[y]);
			x++;
			break;
		case "6":
			str[x]='6';
			number[y] = String.valueOf(str,0,x+1);
			result.setText(number[y]);
			x++;
			break;
		case "7":
			str[x]='7';
			number[y] = String.valueOf(str,0,x+1);
			result.setText(number[y]);
			x++;
			break;
		case "8":
			str[x]='8';
			number[y] = String.valueOf(str,0,x+1);
			result.setText(number[y]);
			x++;
			break;
		case "9":
			str[x]='9';
			number[y] = String.valueOf(str,0,x+1);
			result.setText(number[y]);
			x++;
			break;
		case ".":
			if(flag==0) {
				if(x==0) {
					str[x]='0';
					str[x+1]='.';
					number[y] = String.valueOf(str,0,x+2);
					x++;
				}
				else {
					str[x]='.';
					number[y] = String.valueOf(str,0,x+1);
				}
				result.setText(number[y]);
				x++;
				flag=1;
			}
			break;
		}
	}
	//加减乘除运算结果
	public void Result(){
		switch(c) {
		case "+":
			n1= Double.valueOf(number[y-1]);
			n2= Double.valueOf(number[y]);
			n1=n1+n2;
			result.setText(Judge(n1));
			number[y] = String.valueOf(n1);
			break;
		case "-":
			n1= Double.valueOf(number[y-1]);
			n2= Double.valueOf(number[y]);
			n1=n1-n2;
			result.setText(Judge(n1));
			number[y] = String.valueOf(n1);
			break;
		case "*":
			n1= Double.valueOf(number[y-1]);
			n2= Double.valueOf(number[y]);
			n1=n1*n2;
			result.setText(Judge(n1));
			number[y] = String.valueOf(n1);
			break;
		case "/":
			n1= Double.valueOf(number[y-1]);
			n2= Double.valueOf(number[y]);
			n1=n1/n2;
			result.setText(Judge(n1));
			number[y] = String.valueOf(n1);
			break;
		}
	}
	//内存运算
	public void Memory(String string) {
		DecimalFormat format2 = new DecimalFormat(",#.#");//避免Double.valueof()无法转换带有逗号的字符串
		M2 = number[y];
		try {
			n1 = format2.parse(M1).doubleValue();
		} catch (ParseException e1) {
			// TODO 自动生成的 catch 块
			e1.printStackTrace();
		}
		n2 = Double.valueOf(M2);
		if(string == "M+") {
			n1 = n1 + n2;
		}
		else {
			n1 = n1 - n2;
		}
		M1 = Judge(n1);
		M.setText(M1);
	}
	//为了让输出的整数没有小数形式
	public String Judge(double num) {
		NumberFormat nf = NumberFormat.getInstance();//将数值转换为String类型(只保留三位小数),会舍去整数后的小数形式
		double num1 = num - (int)num;
		if(num1>0) {
			return String.valueOf(num);
		}
		else {
			return nf.format(num);
		}
	}
	//主函数
	public static void main(String args[]) {
		Calculator cl = new Calculator();
	}
}

总结

感觉直接贴个代码不太好,但我又不知该解释啥,感觉没啥内容,大家就在评论区交流吧。一起进步一起进步。

你可能感兴趣的:(java)