使用java来实现一个简单的计算器
最近使用java制作了一个计算器,菜单栏里的功能没有实现,只是写一个版式,仅仅实现了计算功能 ,如果想要实现菜单栏功能可自行在该代码的基础上去实现。
话不多说直接上代码package test;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class calculate extends JFrame implements ActionListener {
private Container ct;
private JButton[] jbs;
private String[] str;
private JTextField jTextField;
//cal[0]用来存储第一次输入的数
//cal[1]用来存储运算符(+,-,*,/,%)
//cal[2]用来存储第二次输入的数
//cal[3]用来存储结果
//cal[4]用来存储MS键所存储的数
//cal[5]用来获取要存入的值(用来给cal[4]赋值)
private String[] cal = {"","","","","",""};
//_count和_count1始终相反,如果_count为true则表示正在输入cal[0]反之表示cal[0]输入完成,该输入cal[2]
//当点过等号后将cal[3]的值赋给cal[0]
private boolean _count = true;
private boolean _count1 = false;
public calculate() {
super("计算器");
jbs = new JButton[28];
ct = this.getContentPane();
this.setBounds(100, 100, 315, 400);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
ct.setLayout(null);
//菜单栏
JMenuBar jMenuBar = new JMenuBar();
JMenu jm = new JMenu("查看(V)");
JMenu jm1 = new JMenu("编辑(E)");
JMenu jm2 = new JMenu("帮助(H)");
jMenuBar.add(jm);
jMenuBar.add(jm1);
jMenuBar.add(jm2);
this.setJMenuBar(jMenuBar);
//输出框
jTextField = new JTextField("0");
jTextField.setFont(new Font("宋体", Font.BOLD, 25));
jTextField.setEditable(false);
jTextField.setHorizontalAlignment(JTextField.RIGHT);
jTextField.setBounds(5, 5, 285, 65);
ct.add(jTextField);
//按键 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
str = new String[]{"MC", "MR", "MS", "M+", "M-", "←", "CE", "C", "±", "√", "7", "8", "9", "/", "%", "4", "5", "6", "*", "1/x", "1", "2", "3", "-", "=", "0", ".", "+"};
int k = 0;
for (int i = 75; i <= 195; i = i + 40) {
for (int init = 10; init <= 290; init = init + 57) {
JButton jButton = new JButton(str[k]);
jbs[k] = jButton;
jButton.setBounds(init, i, 52, 35);
ct.add(jButton);
k++;
System.out.println(k);
}
}
for (int i = 235; i < 265; i = i + 40) {
for (int j = 10; j <= 181; j = j + 57) {
JButton jButton = new JButton(str[k]);</