Repository navigation
Expand file tree
/
Copy pathCalcApplet.java
More file actions
77 lines (77 loc) · 1.63 KB
/
Copy pathCalcApplet.java
File metadata and controls
77 lines (77 loc) · 1.63 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
package chapter17;
/* CalcApplet.java */
/* This is the Applet form of the Precedding Calculator Application Program defined by CalcApp.java */
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class CalcApplet extends Applet {
public void init() {
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{
calculate(Double.parseDouble(display.getText()));
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);
}
}