-
Notifications
You must be signed in to change notification settings - Fork 3
/
Calculator.java
96 lines (82 loc) · 2.53 KB
/
Calculator.java
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
// creating calculator in Java
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Calculator extends JPanel implements ActionListener {
private JTextField display = new JTextField("0");
private double result = 0;
private String operator = "=";
private boolean calculating = true;
public Calculator() {
setLayout(new BorderLayout());
display.setEditable(false);
add(display, "North");
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(4, 4));
String buttonLabels = "789/456*123-0.=+";
for (int i = 0; i < buttonLabels.length(); i++) {
JButton b = new JButton(buttonLabels.substring(i, i + 1));
panel.add(b);
b.addActionListener(this);
}
add(panel, "Center");
}
public void actionPerformed(ActionEvent evt) {
String cmd = evt.getActionCommand();
if ('0' <= cmd.charAt(0) && cmd.charAt(0) <= '9' || cmd.equals(".")) {
if (calculating)
display.setText(cmd);
else
display.setText(display.getText() + cmd);
calculating = false;
} else {
if (calculating) {
if (cmd.equals("-")) {
display.setText(cmd);
calculating = false;
} else
operator = cmd;
} else {
double x = Double.parseDouble(display.getText());
calculate(x);
operator = cmd;
calculating = true;
}
}
}
private void calculate(double n) {
if (operator.equals("+"))
result += n;
else if (operator.equals("-"))
result -= n;
else if (operator.equals("*"))
result *= n;
else if (operator.equals("/"))
result /= n;
else if (operator.equals("="))
result = n;
display.setText("" + result);
}
public static void main(String[] args) {
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame();
frame.setTitle("Calculator");
frame.setSize(200, 200);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
Container contentPane = frame.getContentPane();
contentPane.add(new Calculator());
frame.show();
}
}