效果如下
代码实现
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class SimpleCalculator {
private JFrame frame;
private JTextField numField1;
private JTextField numField2;
private JTextField resultField;
private JButton addButton;
private JButton subtractButton;
private JButton multiplyButton;
private JButton divideButton;
public SimpleCalculator() {
frame = new JFrame("简易计算器");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridLayout(5, 1));
frame.setResizable(false); // Disable maximizing
JPanel inputPanel = new JPanel();
numField1 = new JTextField(5);
numField2 = new JTextField(5);
resultField = new JTextField(5);
resultField.setEditable(false);
inputPanel.add(new JLabel("Number 1:"));
inputPanel.add(numField1);
inputPanel.add(new JLabel("Number 2:"));
inputPanel.add(numField2);
inputPanel.add(new JLabel("Result:"));
inputPanel.add(resultField);
JPanel buttonPanel = new JPanel();
addButton = new JButton("+");
subtractButton = new JButton("-");
multiplyButton = new JButton("*");
divideButton = new JButton("/");
addButton.addActionListener(new OperationListener("+"));
subtractButton.addActionListener(new OperationListener("-"));
multiplyButton.addActionListener(new OperationListener("*"));
divideButton.addActionListener(new OperationListener("/"));
buttonPanel.add(addButton);
buttonPanel.add(subtractButton);
buttonPanel.add(multiplyButton);
buttonPanel.add(divideButton);
frame.add(inputPanel);
frame.add(buttonPanel);
frame.pack();
frame.setLocationRelativeTo(null); // Place the frame in the center of the screen
frame.setVisible(true);
}
private class OperationListener implements ActionListener {
private String operation;
public OperationListener(String operation) {
this.operation = operation;
}
@Override
public void actionPerformed(ActionEvent e) {
double num1 = Double.parseDouble(numField1.getText());
double num2 = Double.parseDouble(numField2.getText());
double result = 0;
switch (operation) {
case "+":
result = num1 + num2;
break;
case "-":
result = num1 - num2;
break;
case "*":
result = num1 * num2;
break;
case "/":
if (num2 != 0) {
result = num1 / num2;
} else {
JOptionPane.showMessageDialog(frame, "Cannot divide by zero!");
return;
}
break;
}
resultField.setText(String.valueOf(result));
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(SimpleCalculator::new);
}
}