import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.*;
/**
* GUI设计进阶+事件处理
* 时间:2019.11.13
* 完成人:梁达林
*/
public class Main {
public static void main(String[] args) {
Calculator calculator = new Calculator();
}
}
class Calculator extends JFrame {
private double result = 0;
private int count = 0;
public Calculator() {
this.setSize(330, 399);
this.setTitle("计算器");
init();
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void init() {
this.setLayout(new BorderLayout());
/*
* 总体布局为边框式布局
* 总体边框式布局north放置文本框
*/
JTextField textField = new JTextField();
textField.setPreferredSize(new Dimension(this.getWidth(), 50));
this.add(textField, BorderLayout.NORTH);
/*
* 总体边框式布局center放置@panel(边框式布局)
* @panel边框式布局north放置@panelN(网格布局)
* @panel边框式布局center放置@panelC(卡片式布局)
* @panelC卡片来切换@panel0(标准)和@panel1(科学)两种模式
* @panel0,@panel1均为网格布局
*/
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
this.add(panel, BorderLayout.CENTER);
JPanel panelN = new JPanel();
panelN.setLayout(new GridLayout(1, 6));
JButton MC = new JButton("MC");
JButton MR = new JButton("MR");
JButton M0 = new JButton("M+");
JButton M1 = new JButton("M-");
JButton MS = new JButton("MS");
JButton M = new JButton("M");
panelN.add(MC);
panelN.add(MR);
panelN.add(M0);
panelN.add(M1);
panelN.add(MS);
panelN.add(M);
panel.add(panelN, BorderLayout.NORTH);
CardLayout cardLayout = new CardLayout();
JPanel panelC = new JPanel();
panelC.setLayout(cardLayout);
JPanel panel0 = new JPanel();
panel0.setLayout(new GridLayout(6, 4));
JButton[] standredButton = new JButton[24];
String str[] = {"%", "√", "x²", "1/x", "CE", "C", "×", "/",
"7", "8", "9", "*", "4", "5", "6", "-",
"1", "2", "3", "+", "±", "0", ".", "="};
for (int i = 0; i < standredButton.length; i++) {
standredButton[i] = new JButton(str[i]);
String text = standredButton[i].getText();
standredButton[i].addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if (text.equals("CE") || text.equals("C")) {
textField.setText("");
} else if (text.equals("=")) {
String expression = textField.getText();
Calculate cal = new Calculate();
textField.setText(cal.evaluateExpression(expression) + "");
} else if (text.equals("%")) { } else if (text.equals("√")) {
result = Double.parseDouble(textField.getText());
result = Math.sqrt(result);
textField.setText(result + "");
} else if (text.equals("x²")) {
result = Double.parseDouble(textField.getText());
result *= result;
textField.setText(result + "");
} else if (text.equals("1/x")) {
result = Double.parseDouble(textField.getText());
result = 1 / result;
textField.setText(result + "");
} else if (text.equals("±")) {
if (count == 0) {
textField.setText(textField.getText() + "-");
count = 1;
} else {
textField.setText(textField.getText() + "+");
count = 0;
}
} else if (text.equals("×")) {
textField.setText(textField.getText().substring(0, textField.getText().length() - 1));
} else {
textField.setText(textField.getText() + text);
}
}
}
);
panel0.add(standredButton[i]);
}
panelC.add(panel0);
JPanel panel1 = new JPanel();
panel1.setLayout(new GridLayout(7, 5));
JButton scienceButton[] = new JButton[35];
String str1[] = {
"x²", "x^y", "sin", "cos", "tan",
"√", "10^x", "log", "Exp", "Mod",
"↑", "CE", "C", "×", "/",
"π", "7", "8", "9", "*",
"n!", "4", "5", "6", "-",
"±", "1", "2", "3", "+",
"(", ")", "0", ".", "="
};
for (int i = 0; i < str1.length; i++) {
scienceButton[i] = new JButton(str1[i]);
//scienceButton[i].addActionListener();
panel1.add(scienceButton[i]);
}
panelC.add(panel1);
panel.add(panelC, BorderLayout.CENTER);
/*
* 菜单
*/
JMenuBar menuBar = new JMenuBar();
this.setJMenuBar(menuBar);
JMenu modelMenu = new JMenu("模式");
menuBar.add(modelMenu);
JMenuItem standred = new JMenuItem("标准");
standred.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
cardLayout.first(panelC);
}
});
modelMenu.add(standred);
JMenuItem science = new JMenuItem("科学");
science.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
cardLayout.last(panelC);
}
});
modelMenu.add(science);
}
}
class Calculate {
/*使用空格分割字符串,以便后面使用分割函数使得将字符串分割成数组*/
public String insetBlanks(String s) {
String result = "";
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(' || s.charAt(i) == ')' ||
s.charAt(i) == '+' || s.charAt(i) == '-'
|| s.charAt(i) == '*' || s.charAt(i) == '/')
result += " " + s.charAt(i) + " ";
else
result += s.charAt(i);
}
return result;
}
public double evaluateExpression(String expression) {
Stack<Double> operandStack = new Stack<>();
Stack<Character> operatorStack = new Stack<>();
expression = insetBlanks(expression);
String[] tokens = expression.split(" ");
for (String token : tokens) {
if (token.length() == 0) /*如果是空格的话就继续循环,什么也不操作*/
continue;
/*如果是加减的话,因为加减的优先级最低,因此这里的只要遇到加减号,无论操作符栈中的是什么运算符都要运算*/
else if (token.charAt(0) == '+' || token.charAt(0) == '-') {
/*当栈不是空的,并且栈中最上面的一个元素是加减乘除的人任意一个*/
while (!operatorStack.isEmpty() && (operatorStack.peek() == '-' || operatorStack.peek() == '+' || operatorStack.peek() == '/' || operatorStack.peek() == '*')) {
processAnOperator(operandStack, operatorStack); //开始运算
}
operatorStack.push(token.charAt(0)); //运算完之后将当前的运算符入栈
}
/*当前运算符是乘除的时候,因为优先级高于加减,因此要判断最上面的是否是乘除,如果是乘除就运算,否则的话直接入栈*/
else if (token.charAt(0) == '*' || token.charAt(0) == '/') {
while (!operatorStack.isEmpty() && (operatorStack.peek() == '/' || operatorStack.peek() == '*')) {
processAnOperator(operandStack, operatorStack);
}
operatorStack.push(token.charAt(0)); //将当前操作符入栈
}
/*如果是左括号的话直接入栈,什么也不用操作,trim()函数是用来去除空格的,由于上面的分割操作可能会令操作符带有空格*/
else if (token.trim().charAt(0) == '(') {
operatorStack.push('(');
}
/*如果是右括号的话,清除栈中的运算符直至左括号*/
else if (token.trim().charAt(0) == ')') {
while (operatorStack.peek() != '(') {
processAnOperator(operandStack, operatorStack); //开始运算
}
operatorStack.pop(); /*这里的是运算完之后清除左括号*/
}
/*这里如果是数字的话直接如数据的栈*/
else {
operandStack.push(Double.parseDouble(token)); /*将数字字符串转换成数字然后压入栈中*/
}
}
/*最后当栈中不是空的时候继续运算,知道栈中为空即可*/
while (!operatorStack.isEmpty()) {
processAnOperator(operandStack, operatorStack);
}
return operandStack.pop(); /*此时数据栈中的数据就是运算的结果*/
}
/*处理栈中的两个数据,然后将栈中的两个数据运算之后将结果存储在栈中*/
public void processAnOperator(Stack<Double> operandStack, Stack<Character> operatorStack) {
char op = operatorStack.pop(); /*弹出一个操作符*/
Double op1 = operandStack.pop(); /*从存储数据的栈中弹出连个两个数用来和操作符op运算*/
Double op2 = operandStack.pop();
if (op == '+') /*如果操作符为+就执行加运算*/
operandStack.push(op1 + op2);
else if (op == '-')
operandStack.push(op2 - op1);/*因为这个是栈的结构,自然是上面的数字是后面的,因此用op2-op1*/
else if (op == '*')
operandStack.push(op1 * op2);
else if (op == '/')
operandStack.push(op2 / op1);
}
}
运行环境:IDEA
运行截图如图:

附:简单一点的请见https://blog.csdn.net/pointer_5/article/details/103073425
本文介绍了如何在IDEA环境下,使用JavaGUI设计并实现一个计算器的用户界面。提供了运行截图,并给出了一个简单的计算器源码链接供参考。
1万+

被折叠的 条评论
为什么被折叠?



