import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Calculator extends JFrame implements ActionListener {
private final String[] content = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "+", "-", "*", "/", "%", "sqrt", "="};
private final JPanel panel = new JPanel();
private final JTextField text = new JTextField(25);
private final JButton button = new JButton("C");
private final JPanel panel1 = new JPanel(new GridLayout(4, 4, 10, 10));
private final JButton[] button1 = new JButton[content.length];
public Calculator() {
this.init();
this.northComponent();
this.centerComponent();
}
public void init() {
this.setTitle("计算器");
this.setSize(400, 400);
this.setLayout(new BorderLayout());
this.setResizable(false);
}
//上方文本框及C(清除按钮)的实现
public void northComponent() {
panel.add(text);
panel.add(button);
this.add(panel, BorderLayout.NORTH);
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
text.setText("");
}
});
}
//下方按钮的实现
public void centerComponent() {
this.panel1.setLayout(new GridLayout(4, 4, 4, 4));
this.add(panel1, BorderLayout.CENTER);
//给按钮添加监听事件
for (int i = 0; i < content.length; i++) {
button1[i] = new JButton(content[i]);
panel1.add(button1[i]);
button1[i].addActionListener(this);
}
}
//运算功能的实现
private String firstInput=null;
private String operate=null;
@Override
public void actionPerformed(ActionEvent e) {
String actionCommand = e.getActionCommand();
if ("0123456789".contains(actionCommand)) {
this.text.setText(text.getText() + actionCommand);
this.text.setHorizontalAlignment(JTextField.RIGHT);
} else if (actionCommand.matches("[\\+\\-*/%]||(sqrt)")) {
operate=actionCommand;
firstInput=this.text.getText();
this.text.setText("");
}
else if(actionCommand.equals("=")) {
double result = 0;
double num1 = Double.parseDouble(firstInput);
if ("sqrt".equals(operate)) {
result = Math.sqrt(num1);
} else {
double num2 = Double.parseDouble(text.getText());
switch (operate) {
case "+":
result = num1 + num2;
break;
case "-":
result = num1 - num2;
break;
case "*":
result = num1 * num2;
break;
case "/":
result = num1 / num2;
break;
case "%":
result = num1 % num2;
break;
}
}
this.text.setText("" + result);
}
}
//主程序入口
public static void main(String[] args) {
Calculator calculator = new Calculator();
calculator.setVisible(true);
}
}
[Java]利用GUI和监听事件实现计算机
于 2022-10-31 09:35:40 首次发布