1// Aim: Program to perform GUI operations (Calculator).
2import javax.swing.*;
3import java.awt.*;
4import java.awt.event.ActionEvent;
5import java.awt.event.ActionListener;
6
7public class Calculator1 extends JFrame implements ActionListener {
8 private JTextField display;
9 private double num1, num2, result;
10 private char operator;
11
12 public Calculator1() {
13 setTitle("Simple Calculator");
14 setSize(400, 500);
15 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
16 setLayout(new BorderLayout());
17
18 display = new JTextField();
19 display.setEditable(false);
20 display.setFont(new Font("Arial", Font.BOLD, 24));
21 add(display, BorderLayout.NORTH);
22
23 JPanel panel = new JPanel();
24 panel.setLayout(new GridLayout(4, 4));
25
26 String[] buttons = {
27 "7", "8", "9", "/",
28 "4", "5", "6", "*",
29 "1", "2", "3", "-",
30 "0", "C", "=", "+"
31 };
32
33 for (String text : buttons) {
34 JButton button = new JButton(text);
35 button.setFont(new Font("Arial", Font.BOLD, 24));
36 button.addActionListener(this);
37 panel.add(button);
38 }
39
40 add(panel, BorderLayout.CENTER);
41 }
42
43 public void actionPerformed(ActionEvent e) {
44 String command = e.getActionCommand();
45
46 if (command.charAt(0) >= '0' && command.charAt(0) <= '9') {
47 display.setText(display.getText() + command);
48 } else if (command.charAt(0) == 'C') {
49 display.setText("");
50 num1 = num2 = result = 0;
51 operator = '\0';
52 } else if (command.charAt(0) == '=') {
53 num2 = Double.parseDouble(display.getText());
54 switch (operator) {
55 case '+':
56 result = num1 + num2;
57 break;
58 case '-':
59 result = num1 - num2;
60 break;
61 case '*':
62 result = num1 * num2;
63 break;
64 case '/':
65 try {
66 result = num1 / num2;
67 } catch (ArithmeticException ex) {
68 display.setText("Error");
69 return;
70 }
71 break;
72 }
73 display.setText(String.valueOf(result));
74 } else {
75 if (!display.getText().isEmpty()) {
76 num1 = Double.parseDouble(display.getText());
77 operator = command.charAt(0);
78 display.setText("");
79 }
80 }
81 }
82
83 public static void main(String[] args) {
84 SwingUtilities.invokeLater(() -> {
85 Calculator1 calculator = new Calculator1();
86 calculator.setVisible(true);
87 });
88 }
89}