/
Calculator.java
90 lines (78 loc) · 2.19 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
// Calculator.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class CalculatorPanel extends JPanel
implements ActionListener
{ public CalculatorPanel()
{ setLayout(new BorderLayout());
display = new JTextField("0");
display.setEditable(false);
add(display, "North");
JPanel p = new JPanel();
p.setLayout(new GridLayout(4, 4));
String buttons = "789/456*123-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)
{ JButton b = new JButton(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 += n;
else if (op.equals("-")) arg -= n;
else if (op.equals("*")) arg *= n;
else if (op.equals("/")) arg /= n;
else if (op.equals("=")) arg = n;
display.setText("" + arg);
}
private JTextField display;
private double arg = 0;
private String op = "=";
private boolean start = true;
}
class CalculatorFrame extends JFrame
{ public CalculatorFrame()
{ setTitle("Calculator");
setSize(200, 200);
addWindowListener(new WindowAdapter()
{ public void windowClosing(WindowEvent e)
{ System.exit(0);
}
} );
Container contentPane = getContentPane();
contentPane.add(new CalculatorPanel());
}
}
public class Calculator
{ public static void main(String[] args)
{ JFrame frame = new CalculatorFrame();
frame.show();
}
}