You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
85 lines
2.7 KiB
85 lines
2.7 KiB
import javax.swing.*;
|
|
import java.awt.*;
|
|
import java.awt.event.ActionEvent;
|
|
import java.awt.event.ActionListener;
|
|
|
|
public class Code extends JFrame implements ActionListener {
|
|
private JTextField display;
|
|
private String operator;
|
|
private double firstNumber, secondNumber, result;
|
|
|
|
public Code() {
|
|
// 设置窗口标题
|
|
setTitle("jisuanqi");
|
|
setSize(300, 400);
|
|
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
|
|
setLocationRelativeTo(null);
|
|
|
|
// 创建显示屏
|
|
display = new JTextField();
|
|
display.setFont(new Font("Arial", Font.BOLD, 24));
|
|
display.setHorizontalAlignment(SwingConstants.RIGHT);
|
|
display.setEditable(false);
|
|
|
|
// 创建按钮面板
|
|
JPanel buttonPanel = new JPanel();
|
|
buttonPanel.setLayout(new GridLayout(4, 4, 10, 10));
|
|
|
|
String[] buttonLabels = {
|
|
"7", "8", "9", "/",
|
|
"4", "5", "6", "*",
|
|
"1", "2", "3", "-",
|
|
"0", ".", "=", "+"
|
|
};
|
|
|
|
for (String label : buttonLabels) {
|
|
JButton button = new JButton(label);
|
|
button.setFont(new Font("Arial", Font.BOLD, 20));
|
|
button.addActionListener(this);
|
|
buttonPanel.add(button);
|
|
}
|
|
|
|
// 添加组件到主窗口
|
|
setLayout(new BorderLayout());
|
|
add(display, BorderLayout.NORTH);
|
|
add(buttonPanel, BorderLayout.CENTER);
|
|
}
|
|
|
|
@Override
|
|
public void actionPerformed(ActionEvent e) {
|
|
String command = e.getActionCommand();
|
|
|
|
if (command.charAt(0) >= '0' && command.charAt(0) <= '9' || command.equals(".")) {
|
|
display.setText(display.getText() + command);
|
|
} else if (command.equals("=")) {
|
|
secondNumber = Double.parseDouble(display.getText());
|
|
switch (operator) {
|
|
case "+":
|
|
result = firstNumber + secondNumber;
|
|
break;
|
|
case "-":
|
|
result = firstNumber - secondNumber;
|
|
break;
|
|
case "*":
|
|
result = firstNumber * secondNumber;
|
|
break;
|
|
case "/":
|
|
result = secondNumber != 0 ? firstNumber / secondNumber : 0;
|
|
break;
|
|
}
|
|
display.setText(String.valueOf(result));
|
|
} else {
|
|
firstNumber = Double.parseDouble(display.getText());
|
|
operator = command;
|
|
display.setText("");
|
|
}
|
|
}
|
|
|
|
public static void main(String[] args) {
|
|
SwingUtilities.invokeLater(() -> {
|
|
Code calculator = new Code();
|
|
calculator.setVisible(true);
|
|
});
|
|
}
|
|
}
|