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.
93 lines
3.2 KiB
93 lines
3.2 KiB
package jisuanji;
|
|
|
|
import javax.swing.*;
|
|
import java.awt.*;
|
|
import java.awt.event.ActionEvent;
|
|
import java.awt.event.ActionListener;
|
|
|
|
public class CalculatorGUI extends JFrame {
|
|
private JTextField display;
|
|
private Calculator calculator = new Calculator();
|
|
private double firstNumber = 0;
|
|
private double secondNumber = 0;
|
|
private String operation = "";
|
|
private boolean isOperationClicked = false;
|
|
|
|
public CalculatorGUI() {
|
|
setTitle("简易计算器");
|
|
setSize(400, 600);
|
|
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
|
|
setLocationRelativeTo(null);
|
|
|
|
display = new JTextField();
|
|
display.setEditable(false);
|
|
display.setFont(new Font("Arial", Font.PLAIN, 40));
|
|
display.setHorizontalAlignment(JTextField.RIGHT);
|
|
display.setBorder(BorderFactory.createLineBorder(Color.BLACK));
|
|
|
|
JPanel panel = new JPanel();
|
|
panel.setLayout(new GridLayout(4, 4, 10, 10));
|
|
|
|
String[] buttons = {
|
|
"7", "8", "9", "/",
|
|
"4", "5", "6", "*",
|
|
"1", "2", "3", "-",
|
|
"0", ".", "=", "+"
|
|
};
|
|
|
|
for (String buttonText : buttons) {
|
|
JButton button = new JButton(buttonText);
|
|
button.setFont(new Font("Arial", Font.PLAIN, 24));
|
|
button.addActionListener(new ButtonClickListener());
|
|
panel.add(button);
|
|
}
|
|
|
|
add(display, BorderLayout.NORTH);
|
|
add(panel, BorderLayout.CENTER);
|
|
|
|
setVisible(true);
|
|
}
|
|
|
|
private class ButtonClickListener implements ActionListener {
|
|
@Override
|
|
public void actionPerformed(ActionEvent e) {
|
|
String command = e.getActionCommand();
|
|
|
|
if ("0123456789.".indexOf(command) >= 0) {
|
|
display.setText(display.getText() + command);
|
|
isOperationClicked = false;
|
|
} else if ("+*/-=".indexOf(command) >= 0) {
|
|
if (!isOperationClicked) {
|
|
firstNumber = Double.parseDouble(display.getText());
|
|
operation = command;
|
|
isOperationClicked = true;
|
|
display.setText("");
|
|
} else if (command.equals("=")) {
|
|
secondNumber = Double.parseDouble(display.getText());
|
|
double result = 0;
|
|
switch (operation) {
|
|
case "+":
|
|
result = calculator.add(firstNumber, secondNumber);
|
|
break;
|
|
case "-":
|
|
result = calculator.subtract(firstNumber, secondNumber);
|
|
break;
|
|
case "*":
|
|
result = calculator.multiply(firstNumber, secondNumber);
|
|
break;
|
|
case "/":
|
|
result = calculator.divide(firstNumber, secondNumber);
|
|
break;
|
|
}
|
|
display.setText(String.valueOf(result));
|
|
isOperationClicked = false;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
public static void main(String[] args) {
|
|
new CalculatorGUI();
|
|
}
|
|
}
|