-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSimpleCalculator.java
More file actions
73 lines (62 loc) · 2.39 KB
/
SimpleCalculator.java
File metadata and controls
73 lines (62 loc) · 2.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class SimpleCalculator {
private JFrame frame;
private JTextField textField;
private double num1, num2, result;
private char operator;
public SimpleCalculator() {
frame = new JFrame("Calculator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 400);
frame.setLayout(new BorderLayout());
textField = new JTextField();
textField.setFont(new Font("Arial", Font.BOLD, 18));
textField.setHorizontalAlignment(JTextField.RIGHT);
frame.add(textField, BorderLayout.NORTH);
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(4, 4));
frame.add(panel, BorderLayout.CENTER);
String[] buttons = {
"7", "8", "9", "/",
"4", "5", "6", "*",
"1", "2", "3", "-",
"0", "C", "=", "+"
};
for (String text : buttons) {
JButton button = new JButton(text);
button.setFont(new Font("Arial", Font.BOLD, 18));
panel.add(button);
button.addActionListener(new ButtonClickListener());
}
frame.setVisible(true);
}
private class ButtonClickListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if (command.charAt(0) >= '0' && command.charAt(0) <= '9') {
textField.setText(textField.getText() + command);
} else if (command.equals("C")) {
textField.setText("");
} else if (command.equals("=")) {
num2 = Double.parseDouble(textField.getText());
switch (operator) {
case '+': result = num1 + num2; break;
case '-': result = num1 - num2; break;
case '*': result = num1 * num2; break;
case '/': result = num1 / num2; break;
}
textField.setText(String.valueOf(result));
} else {
num1 = Double.parseDouble(textField.getText());
operator = command.charAt(0);
textField.setText("");
}
}
}
public static void main(String[] args) {
new SimpleCalculator();
}
}