-
Notifications
You must be signed in to change notification settings - Fork 3
/
CalculatorSwing.java
91 lines (88 loc) · 3.03 KB
/
CalculatorSwing.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
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class CalculatorSwing extends JFrame {
JTextField t1, t2, t3;
JButton b1, b2, b3, b4;
JLabel l1, l2, l3;
public CalculatorSwing() {
t1 = new JTextField(10);
t2 = new JTextField(10);
t3 = new JTextField(10);
b1 = new JButton("+");
b2 = new JButton("-");
b3 = new JButton("*");
b4 = new JButton("/");
l1 = new JLabel("First Number");
l2 = new JLabel("Second Number");
l3 = new JLabel("Result");
setLayout(new FlowLayout());
add(l1);
add(t1);
add(l2);
add(t2);
add(l3);
add(t3);
add(b1);
add(b2);
add(b3);
add(b4);
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
try {
int a = Integer.parseInt(t1.getText());
int b = Integer.parseInt(t2.getText());
int c = a + b;
t3.setText(String.valueOf(c));
} catch (NumberFormatException e) {
t3.setText("Invalid input");
}
}
});
b2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
try {
int a = Integer.parseInt(t1.getText());
int b = Integer.parseInt(t2.getText());
int c = a - b;
t3.setText(String.valueOf(c));
} catch (NumberFormatException e) {
t3.setText("Invalid input");
}
}
});
b3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
try {
int a = Integer.parseInt(t1.getText());
int b = Integer.parseInt(t2.getText());
int c = a * b;
t3.setText(String.valueOf(c));
} catch (NumberFormatException e) {
t3.setText("Invalid input");
}
}
});
b4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
try {
int a = Integer.parseInt(t1.getText());
int b = Integer.parseInt(t2.getText());
if (b == 0) throw new ArithmeticException();
int c = a / b;
t3.setText(String.valueOf(c));
} catch (NumberFormatException e) {
t3.setText("Invalid input");
} catch (ArithmeticException e) {
t3.setText("Cannot divide by zero");
}
}
});
}
public static void main(String[] args) {
CalculatorSwing c = new CalculatorSwing();
c.setSize(400, 400);
c.setVisible(true);
c.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}