Java实现简单的计算器(原创)

初学Java中的Swing,写了一个简单的计算器,和大家分享一下!

支持键盘和鼠标操作

支持多个数运算。例如:输入1+2+3,结果是6!

源代码:

import java.awt.*; import javax.swing.*; import java.awt.event.*; class GUI extends JFrame implements ActionListener,KeyListener { JTextField textField; private String strx = ""; private String stry =""; private String str =""; private String op=""; private String result=""; private int flag=1; private String strtemp; private float x; private float y; public GUI() { super(); this.setTitle("计算器"); this.setVisible(true); this.setBounds(800, 400, 280, 250); this.setResizable(true); this.addKeyListener(this); BorderLayout borLayout = new BorderLayout(); this.getContentPane().setLayout(borLayout); final JPanel viewpanel = new JPanel(); this.getContentPane().add(viewpanel, BorderLayout.NORTH); textField = new JTextField(); textField.setEditable(false); textField.setText("0"); textField.setHorizontalAlignment(SwingConstants.RIGHT); textField.setColumns(20); viewpanel.add(textField); final JPanel bottonPanel = new JPanel(); bottonPanel.setSize(200, 200); GridLayout gri = new GridLayout(4,0); gri.setHgap(10); gri.setVgap(10); bottonPanel.setLayout(gri); String[][] names ={{"1","2","3","+"}, {"4","5","6","-"}, {"7","8","9","*"}, {".","0","=","/"} }; JButton[][] buttons = new JButton[4][4]; for(int i=0;i<4;i++) { for(int j=0;j<4;j++) { buttons[i][j] = new JButton(names[i][j]); buttons[i][j].setName(names[i][j]); buttons[i][j].setSize(40, 35); buttons[i][j].addActionListener(this); bottonPanel.add(buttons[i][j]); } } this.getContentPane().add(bottonPanel,BorderLayout.CENTER); final JLabel label1 = new JLabel(); label1.setPreferredSize(new Dimension(10,0)); this.getContentPane().add(label1,BorderLayout.WEST); final JButton button = new JButton("CE"); button.setName("CE"); button.addActionListener(this); this.getContentPane().add(button,BorderLayout.EAST); } public void calculate() { if(str!="") { System.out.println("strx == "+strx); System.out.println("stry == "+stry); try{ if(strx=="") { strx=strtemp; } x=Float.parseFloat(strx); y=Float.parseFloat(stry); }catch(Exception ex) { ex.printStackTrace(); } if(op=="+") { result = (x + y) + ""; } else if(op=="-") { result = (x - y) + ""; }else if(op=="*") { result = (x * y) + ""; }else { if(y==0) { result="ERROR"; } else{ result = (x / y) + ""; } } } } private void CaculateTemp() { if(op=="*"||op=="+"||op=="-"||op=="/") { calculate(); strx=result; str=result; stry=""; } } private void CE() { strx = ""; stry =""; str =""; op=""; result=""; flag=1; textField.setText("0"); } private void Cacu(String s) { if(s.equals("CE")) { CE(); } else if(s.equals("=")) { calculate(); textField.setText(result); strtemp=result; str=strtemp; stry=""; op=""; } else { if(s.equals("+")) { if(result!="") { str=result; strx=result; } CaculateTemp(); flag=0; op="+"; }else if(s.equals("-")) { if(result!="") { str=result; strx=result; } CaculateTemp(); flag=0; op="-"; }else if(s.equals("*")) { if(result!="") { str=result; strx=result; } CaculateTemp(); flag=0; op="*"; }else if(s.equals("/")) { if(result!="") { str=result; strx=result; } CaculateTemp(); flag=0; op="/"; }else { if(flag==1) { strx = strx + s; System.out.println("strx = "+strx); } if(flag==0) { stry = stry + s; System.out.println("stry = "+stry); } } str = str + s; System.out.println("str = "+str); textField.setText(str); } } public void actionPerformed(ActionEvent e) public void keyTyped(KeyEvent e) public void keyReleased(KeyEvent e) public void keyPressed(KeyEvent e) } public class JSQ { public static void main(String[] args) { GUI a = new GUI(); } }

经过本人多次调试,此程序中仍然存在问题。

1、不能先输入等号

2、不能连续输入多个操作符

3、进行每次运算的时候,都要先清零!

4、运行的时候,出现的窗口要先最小化,再打开,才能显示(不知道为什么)

5、支持键盘和鼠标操作,但是如果一用鼠标操作,就不能再用键盘操作了!(个人觉得,可能监听器加的位置有问题,但又不知道该加到那里可以让键盘,鼠标操作随意切换)

6、可能还有其他问题,所以此处略去n个字!!!!!!

转载于:https://www.cnblogs.com/JPAORM/archive/2011/05/10/2510104.html

评论将由博主筛选后显示,对所有人可见 | 还能输入1000个字符 “速评一下”
``` import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Font; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JTextField; import javax.swing.border.LineBorder; interface Calculable { double CalculateInt(double x, double y); }// 用来定义Lambda表达式的接口 public class Mycalc extends JFrame { private static final long serialVersionUID = 1L; // 用来保存第一个数 private String number1 = ""; // 用来保存第二个数 private String number2 = ""; // 用来保存两个数的运算符 private String operator = ""; // 显示框 JTextField jt = new JTextField("0.0 "); public Mycalc() { setTitle("My first Calc"); setSize(600, 750); setLayout(null); SetCenter(this); setResizable(false); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); addJT(); addButton(); setVisible(true); } void addJT() {// 添加显示框 jt.setBounds(0, 0, 600, 150); // 不允许对显示框进行编辑 jt.setEditable(false); // 显示框内的数据右对齐 jt.setHorizontalAlignment(JTextField.RIGHT); // 设置背景色 jt.setBackground(new Color(100, 100, 100)); // 设置字体属性 jt.setFont(new Font("宋体", Font.BOLD, 20)); add(jt);// 添加 } void addButton() {// 添加操作按钮 JButton jb_7 = new JButton("7"); // 设置按钮边框的属性 jb_7.setBorder(new LineBorder(Color.BLUE, 1)); // 设置按钮的字体属性 jb_7.setFont(new Font("宋体", Font.BOLD, 20)); // 设置按钮的位置及大小 jb_7.setBounds(0, 150, 150, 150); // 添加数字监听者 jb_7.addActionListener(new NumberBtListener()); add(jb_7);// 添加 JButton jb_8 = new JButton("8"); jb_8.setBorder(new LineBorder(Color.BLUE, 1)); jb_8.setFont(new Font("宋体", Font.BOLD, 20)); jb_8.setBounds(150, 150, 150, 150); jb_8.addActionListener(new NumberBtListener()); add(jb_8); JButton jb_9 = new JButton("9"); jb_9.setBorder(new LineBorder(Color.BLUE, 1)); jb_9.setFont(new Font("宋体", Font.BOLD, 20)); jb_9.setBounds(300, 150, 150, 150); jb_9.addActionListener(new NumberBtListener()); add(jb_9); JButton jb_add = new JButton("+"); jb_add.setBounds(450, 150, 150, 150); jb_add.setBorder(new LineBorder(Color.BLUE, 1)); jb_add.setFont(new Font("宋体", Font.BOLD, 20)); jb_add.addActionListener(new Operation()); add(jb_add); JButton jb_4 = new JButton("4"); jb_4.setBorder(new LineBorder(Color.BLUE, 1)); jb_4.setFont(new Font("宋体", Font.BOLD, 20)); jb_4.setBounds(0, 300, 150, 150); jb_4.addActionListener(new NumberBtListener()); add(jb_4); JButton jb_5 = new JButton("5"); jb_5.setBorder(new LineBorder(Color.BLUE, 1)); jb_5.setFont(new Font("宋体", Font.BOLD, 20)); jb_5.setBounds(150, 300, 150, 150); jb_5.addActionListener(new NumberBtListener()); add(jb_5); JButton jb_6 = new JButton("6"); jb_6.setBorder(new LineBorder(Color.BLUE, 1)); jb_6.setFont(new Font("宋体", Font.BOLD, 20)); jb_6.setBounds(300, 300, 150, 150); jb_6.addActionListener(new NumberBtListener()); add(jb_6); JButton jb_cut = new JButton("-"); jb_cut.setBounds(450, 300, 150, 150); jb_cut.setBorder(new LineBorder(Color.BLUE, 1)); jb_cut.setFont(new Font("宋体", Font.BOLD, 20)); jb_cut.addActionListener(new Operation()); add(jb_cut); JButton jb_1 = new JButton("1"); jb_1.setBorder(new LineBorder(Color.BLUE, 1)); jb_1.setFont(new Font("宋体", Font.BOLD, 20)); jb_1.setBounds(0, 450, 150, 150); jb_1.addActionListener(new NumberBtListener()); add(jb_1); JButton jb_2 = new JButton("2"); jb_2.setBorder(new LineBorder(Color.BLUE, 1)); jb_2.setFont(new Font("宋体", Font.BOLD, 20)); jb_2.setBounds(150, 450, 150, 150); jb_2.addActionListener(new NumberBtListener()); add(jb_2); JButton jb_3 = new JButton("3"); jb_3.setBorder(new LineBorder(Color.BLUE, 1)); jb_3.setFont(new Font("宋体", Font.BOLD, 20)); jb_3.setBounds(300, 450, 150, 150); jb_3.addActionListener(new NumberBtListener()); add(jb_3); JButton jb_ride = new JButton("*"); jb_ride.setBounds(450, 450, 150, 150); jb_ride.setBorder(new LineBorder(Color.BLUE, 1)); jb_ride.setFont(new Font("宋体", Font.BOLD, 20)); jb_ride.addActionListener(new Operation()); add(jb_ride); JButton jb_0 = new JButton("0"); jb_0.setBorder(new LineBorder(Color.BLUE, 1)); jb_0.setFont(new Font("宋体", Font.BOLD, 20)); jb_0.setBounds(0, 600, 150, 150); jb_0.addActionListener(new NumberBtListener()); add(jb_0); JButton jb_equal = new JButton("="); jb_equal.setBounds(150, 600, 150, 150); jb_equal.setBorder(new LineBorder(Color.BLUE, 1)); jb_equal.setFont(new Font("宋体", Font.BOLD, 20)); jb_equal.addActionListener(new ClearOrEqual()); add(jb_equal); JButton jb_C = new JButton("C"); jb_C.setBounds(300, 600, 150, 150); jb_C.setBorder(new LineBorder(Color.BLUE, 1)); jb_C.setFont(new Font("宋体", Font.BOLD, 20)); jb_C.addActionListener(new ClearOrEqual()); add(jb_C); JButton jb_divide = new JButton("/"); jb_divide.setBounds(450, 600, 150, 150); jb_divide.setBorder(new LineBorder(Color.BLUE, 1)); jb_divide.setFont(new Font("宋体", Font.BOLD, 20)); jb_divide.addActionListener(new Operation()); add(jb_divide); } public static void main(String[] args) { new Mycalc(); } // 让主窗口最初在屏幕的中间显示 void SetCenter(Component cp) { // 得到屏幕的长度和宽度 Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); int screenheight = dim.height; int screenwidth = dim.width; int x = (screenwidth - cp.getWidth()) / 2; int y = (screenheight - cp.getHeight()) / 2; cp.setLocation(x, y); } /**对数字按钮进行事件监听 * 当未对运算符进行设置时,进行对第一个数的数值进行输入 * 运算符不为空时,对第二个数的数据进行输入 */ class NumberBtListener implements ActionListener { public void actionPerformed(ActionEvent e) { JButton jbt = (JButton) e.getSource(); String content = jbt.getText(); if (!operator.equals("")) { number1 += content; int number = Integer.valueOf(number1); jt.setText(number + " "); } else { number2 += content; int number = Integer.valueOf(number2); jt.setText(number + " "); } } } // 得出运算结果和清空显示框的监听者 class ClearOrEqual implements ActionListener { public void actionPerformed(ActionEvent e) { JButton jbt = (JButton) e.getSource(); String content = jbt.getText(); // number用来存放两个数运算的结果 double number = 0; // num1用来得到第一个数的数值 double num1 = Double.parseDouble(number1); // num2用来得到第二个数的数值 double num2 = Double.parseDouble(number2); // 得到此时运算的方法 Calculable cal = Calculate(operator); switch (content) { case "=": { if (!(operator.equals("") && number2.equals(""))) { // 运算完成 number = cal.CalculateInt(num1, num2); // 将运算完的数值再送给number1 //在多次点击‘=’时,可以进行多次运算 number1 = String.valueOf(number); jt.setText(number + " "); } } break; case "C": { jt.setText("0"); number1 = ""; number2 = ""; operator = ""; } break; } } } // 对运算符按钮进行监听的监听者 class Operation implements ActionListener { public void actionPerformed(ActionEvent e) { JButton jbt = (JButton) e.getSource(); String content = jbt.getText(); // 将按钮的运算符送给operator operator = content; // 将number2置空 number2 = ""; } } // 利用lambda表达式求运算方法 public static Calculable Calculate(String str) { Calculable result; switch (str) { case "+": { result = (x, y) -> (x + y); } break; case "-": { result = (x, y) -> (x - y); } break; case "*": { result = (x, y) -> (x * y); } break; case "/": { result = (x, y) -> (x / y); } break; } return result; } } ```
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页