Advertisement
fahimkamal63

Simple Calculator (using AWT)

Aug 15th, 2019
359
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.12 KB | None | 0 0
  1. /**
  2.  * Simple Calculator (using AWT)
  3.  * Date : 10.08.19
  4.  */
  5. package AWT;
  6. import java.awt.*;
  7. import java.awt.event.*;
  8.  
  9. public class Calculator implements ActionListener {
  10.     TextField tf1, tf2, tf3;
  11.     Button b1, b2, b3, b4;
  12.     Calculator(){
  13.         Frame f = new Frame("Calculator");
  14.         f.setSize(300, 300);
  15.         f.setLayout(null);
  16.         f.setVisible(true);
  17.         Label l1 = new Label("Input 1: ");
  18.         l1.setBounds(50, 50, 40, 20);
  19.         Label l2 = new Label("Input 2: ");
  20.         l2.setBounds(50, 110, 40, 20);
  21.         Label l3 = new Label("Output: ");
  22.         l3.setBounds(50, 170, 40, 20);
  23.        
  24.         tf1 = new TextField();
  25.         tf1.setBounds(100, 50, 100, 20);
  26.        
  27.         tf2 = new TextField();
  28.         tf2.setBounds(100, 110, 100, 20);
  29.        
  30.         tf3 = new TextField();
  31.         tf3.setBounds(100, 170, 100, 20);
  32.         tf3.setEditable(false);
  33.        
  34.         b1 = new Button("+");
  35.         b1.setBounds(50, 200, 30, 30);
  36.         b1.addActionListener(this);
  37.        
  38.         b2 = new Button("-");
  39.         b2.setBounds(90, 200, 30, 30);
  40.         b2.addActionListener(this);
  41.        
  42.         b3 = new Button("*");
  43.         b3.setBounds(130, 200, 30, 30);
  44.         b3.addActionListener(this);
  45.        
  46.         b4 = new Button("/");
  47.         b4.setBounds(170, 200, 30, 30);
  48.         b4.addActionListener(this);
  49.        
  50.         f.add(tf1); f.add(tf2); f.add(tf3);
  51.         f.add(l1); f.add(l2); f.add(l3);
  52.         f.add(b1); f.add(b2); f.add(b3); f.add(b4);
  53.     }
  54.    
  55.     public void actionPerformed(ActionEvent e){
  56.         String in1 = tf1.getText();
  57.         String in2 = tf2.getText();
  58.         double a = Double.parseDouble(in1);
  59.         double b = Double.parseDouble(in2);
  60.         double c = 0;
  61.         if(e.getSource() == b1){ c = a + b; }
  62.         else if(e.getSource() == b2){ c = a - b; }
  63.         else if(e.getSource() == b3){ c = a * b; }
  64.         else if(e.getSource() == b4){ c = a / b; }
  65.         String result = String.valueOf(c);
  66.         tf3.setText(result);
  67.     }
  68.    
  69.     public static void main(String[] args){
  70.         new Calculator();
  71.     }
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement