Professional Documents
Culture Documents
Exp 3
Exp 3
Code:
package calculator;
import java.awt.*;
import java.awt.event.*;
public class CALCULATORRR extends WindowAdapter implements ActionListener {
Frame f;
Label l1, l2, l3, l4;
TextField t1, t2, t3;
Button b1, b2, b3, b4, b5;
CALCULATORRR() {
init();
f.setTitle("Calculator");
f.setSize(400, 400);
f.setLayout(null);
f.setVisible(true);
location();
addComponents();
}
public void init() {
f = new Frame();
f.setBackground(new Color(190, 170, 190));
l1 = new Label("Number 1");
l2 = new Label("Number 2");
l3 = new Label("Result");
l4 = new Label("");
t1 = new TextField(10);
t2 = new TextField(10);
t3 = new TextField(10);
b1 = new Button("+");
b1.setBackground(new Color(190, 170, 190).brighter());
b2 = new Button("-");
b2.setBackground(new Color(190, 170, 190).brighter());
b3 = new Button("*");
b3.setBackground(new Color(190, 170, 190).brighter());
b4 = new Button("/");
b4.setBackground(new Color(190, 170, 190).brighter());
b5 = new Button("Reset");
b5.setBackground(new Color(190, 170, 190).brighter());
}
public void addComponents() {
f.addWindowListener(this);
f.setFont(new Font("Verdana", Font.PLAIN, 16));
f.add(l1);
f.add(l2);
f.add(l3);
f.add(t1);
f.add(t2);
f.add(t3);
f.add(b1);
b1.addActionListener(this);
f.add(b2);
b2.addActionListener(this);
f.add(b3);
b3.addActionListener(this);
f.add(b4);
b4.addActionListener(this);
f.add(b5);
b5.addActionListener(this);
f.add(l4);
}
public void location() {
l1.setBounds(30, 60, 70, 30);
t1.setBounds(105, 60, 80, 30);
l2.setBounds(205, 60, 70, 30);
t2.setBounds(280, 60, 80, 30);
l3.setBounds(120, 130, 60, 30);
t3.setBounds(180, 130, 90, 30);
b1.setBounds(40, 200, 50, 30);
b2.setBounds(130, 200, 50, 30);
b3.setBounds(220, 200, 50, 30);
b4.setBounds(310, 200, 50, 30);
b5.setBounds(150, 270, 100, 30);
l4.setBounds(110, 350, 200, 30);
}
public void actionPerformed(ActionEvent a) {
int result, num1 = 0, num2 = 0;
if (!t1.getText().isEmpty() && !t2.getText().isEmpty()) {
num1 = Integer.parseInt(t1.getText());
num2 = Integer.parseInt(t2.getText());
}
if (a.getSource() == b1) {
result = num1 + num2;
t3.setText(Integer.toString(result));
l4.setText("");
} else if (a.getSource() == b2) {
result = num1 - num2;
t3.setText(Integer.toString(result));
l4.setText("");
} else if (a.getSource() == b3) {
result = num1 * num2;
t3.setText(Integer.toString(result));
l4.setText("");
} else if (a.getSource() == b4) {
if (num2 == 0) {
t3.setText("Math Error");
Output:
1.Addition 2. Subtraction
3.Multiplication 4.Division
5. Error