Simple Calculator With Event TIC
Simple Calculator With Event TIC
import java.awt.event.*;
import javax.swing.*;
public Calculator()
{
setTitle("Simple Calculator");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(null);
lblMsg = new JLabel("Simple Arithmetic Calculator");
lblMsg.setBounds(100, 10, 200, 25);
add(lblMsg);
//Creaging objects for above components
firstLabel = new JLabel("First number: ");
firstText = new JTextField();
secondLabel = new JLabel("Second number: ");
secondText = new JTextField();
resultLabel = new JLabel("Result: ");
thirdText = new JTextField();
thirdText.setEditable(false);
btnAdd = new JButton("ADD");
btnSub = new JButton("SUB");
btnProd = new JButton("PROD");
btnDiv = new JButton("DIV");
//Adding event
btnAdd.addActionListener(this);
btnSub.addActionListener(this);
btnProd.addActionListener(this);
btnDiv.addActionListener(this);
setSize(350, 200);
setLocationRelativeTo(null);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
int a = Integer.parseInt(firstText.getText());
int b = Integer.parseInt(secondText.getText());
if(e.getSource()==btnAdd)
{
int sum = a + b;
thirdText.setText(String.valueOf(sum));
}
if(e.getSource()==btnSub)
{
int s = a - b;
thirdText.setText(String.valueOf(s));
}
if(e.getSource()==btnProd)
{
int p = a * b;
thirdText.setText(String.valueOf(p));
}
if(e.getSource()==btnDiv)
{
float d = (float)a/b;
thirdText.setText(String.valueOf(d));
}
}
}
public class SimpleCalculatorWithEventTIC {
public static void main(String[] args) {
new Calculator();
}
}