Search This Blog

Friday, June 4, 2021

Basic Calculator Using 'GUI' in java

Calculator Using GUI



********************************

 package com.company;


import javax.swing.*;

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;


public class GUI_calculator implements ActionListener {

    float first=0;

    float second=0;

    float third=0;

   private JFrame frame;

   private JPanel panel;

    private JButton b;

   private JButton b1;

   private JButton b2;

   private JButton b3;

   private JButton b4;

    private JButton b5;

    private JButton b6;

    private JButton b7;

   private JLabel label;

    private JLabel label1;

    private JLabel label2;

    public GUI_calculator(){

        frame=new JFrame();

        label=new JLabel("0");

        b=new JButton("++");

        b1=new JButton("+");

        b2=new JButton("-");

        b3=new JButton("*");

        b4=new JButton("/");

        label1=new JLabel("0");

        b5=new JButton("++");

        b6=new JButton("=");

        b7=new JButton("C");

        label2=new JLabel("0");

        b1.addActionListener(this);

        b2.addActionListener(this);

        b3.addActionListener(this);

        b4.addActionListener(this);

        b.addActionListener(this);

        b5.addActionListener(this);

        b6.addActionListener(this);

        b7.addActionListener(this);


        //Panel Content

        panel=new JPanel();

        panel.setBorder(BorderFactory.createEmptyBorder(30,30,10,30));


        panel.add(label);

        panel.add(b);

        panel.add(label1);

        panel.add(b5);

        panel.add(b7);

        panel.add(b1);

        panel.add(b2);

        panel.add(b3);

        panel.add(b4);

        panel.add(b6);

        panel.add(label2);



        panel.setLayout(new GridLayout(0,1));

        frame.add(panel,BorderLayout.CENTER);

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.setTitle("Calculator");

        frame.pack();

        frame.setVisible(true);

    }

    public static void main(String[] args) {

        new GUI_calculator();

    }


    @Override

    public void actionPerformed(ActionEvent e) {

if (e.getSource()==b){

    first++;

    label.setText(""+first);

}

else { }

if (e.getSource()==b5){

    second++;

    label1.setText(""+second);

}

else { }

if (e.getSource()==b1){

    third=first+second;

}

else if (e.getSource()==b2){

    third=first-second;

}

else if (e.getSource()==b3){

    third=first*second;

}

else if (e.getSource()==b4){

    third=first/second;

}

else if (e.getSource()==b7){

    first=0;

    second=0;

    label1.setText(""+second);

    label.setText(""+first);

}

if (e.getSource()==b6){

    label2.setText(""+third);

}

    }

}