MIT-Curricular/OOP/Java/Lab/Week13/Calculator.java

123 lines
3.2 KiB
Java

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Calculator extends JFrame implements ActionListener {
private JTextField display;
private double result = 0;
private String operator = "=";
private boolean calculating = true;
public Calculator() {
display = new JTextField("0", 20);
display.setHorizontalAlignment(JTextField.RIGHT);
display.setEditable(false);
// Create panel with grid layout for buttons
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(4, 4, 5, 5));
String[] buttonLabels = {
"7",
"8",
"9",
"/",
"4",
"5",
"6",
"*",
"1",
"2",
"3",
"-",
"0",
".",
"=",
"+",
};
for (String label : buttonLabels) {
JButton button = new JButton(label);
buttonPanel.add(button);
button.addActionListener(this);
}
JButton clearButton = new JButton("C");
clearButton.addActionListener(e -> {
result = 0;
operator = "=";
calculating = true;
display.setText("0");
});
// Layout
setLayout(new BorderLayout(5, 5));
add(display, BorderLayout.NORTH);
add(buttonPanel, BorderLayout.CENTER);
add(clearButton, BorderLayout.SOUTH);
setTitle("Simple Calculator");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setLocationRelativeTo(null);
}
public void actionPerformed(ActionEvent event) {
String command = event.getActionCommand();
if (
(command.charAt(0) >= '0' && command.charAt(0) <= '9') ||
command.equals(".")
) {
if (calculating) {
display.setText(command);
} else {
display.setText(display.getText() + command);
}
calculating = false;
} else {
if (calculating) {
if (command.equals("-")) {
display.setText(command);
calculating = false;
} else {
operator = command;
}
} else {
double x = Double.parseDouble(display.getText());
calculate(x);
operator = command;
calculating = true;
}
}
}
private void calculate(double n) {
switch (operator) {
case "+":
result += n;
break;
case "-":
result -= n;
break;
case "*":
result *= n;
break;
case "/":
result /= n;
break;
case "=":
result = n;
break;
}
display.setText("" + result);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
new Calculator().setVisible(true);
});
}
}