Repository navigation
Expand file tree
/
Copy pathCalcApp.java
More file actions
96 lines (88 loc) · 2.01 KB
/
Copy pathCalcApp.java
File metadata and controls
96 lines (88 loc) · 2.01 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package chapter17;
/* CalcApp.java */
/* A Simple Calculator Application Program */
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class CalcApp extends Applet{
public static void main(String[] args)
{
Frame frame = new CalculatorFrame();
frame.show();
}
}
class CalculatorFrame extends Frame{
public CalculatorFrame() {
setTitle("Calculator Application");
setSize(400, 200);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);} } );
add(new CalculatorPanel());
}
}
class CalculatorPanel extends Panel implements ActionListener
{
private TextField display;
private double Arg = 0;
private String op = "=";
private boolean start = true;
public CalculatorPanel() {
setLayout(new BorderLayout());
display = new TextField("0");
display.setEditable(false);
add(display, "North");
Panel p = new Panel();
p.setLayout(new GridLayout(4, 4));
String buttons = "123/456*789-0.=+";
for (int i = 0; i < buttons.length(); i++)
addButton(p, buttons.substring(i, i + 1));
add(p, "Center");
}
private void addButton(Container c, String s) {
Button b = new Button(s);
c.add(b);
b.addActionListener(this);
}
public void actionPerformed(ActionEvent evt) {
String s = evt.getActionCommand();
if ('0'<=s.charAt(0)&&s.charAt(0)<='9'||s.equals("."))
{
if (start)
display.setText(s);
else
display.setText(display.getText() + s);
start = false;
}
else {
if (start)
{
if (s.equals("-"))
{
display.setText(s);
start = false;
}
else op = s;
}
else {
double x = Double.parseDouble(display.getText());
calculate(x);
op = s;
start = true;
}
}
}
public void calculate(double n) {
if (op.equals("+"))
Arg = Arg + n;
else if (op.equals("-"))
Arg = Arg -n;
else if (op.equals("*"))
Arg = Arg * n;
else if (op.equals("/"))
Arg = Arg / n;
else if (op.equals("="))
Arg = n;
display.setText("" + Arg);
}
}