Home » Blog » Java Swing : Implementation Of Calculator

Java Swing : Implementation Of Calculator

Swing is a GUI widget toolkit for Java

This article gives you insight of implementation of calculator using swing. It uses swing component like JFrame, JPanel, JTextField and JButton. It implements ActionListener interface to perform some action based on user click. See the code given below.

Implementation

package ajavabasics;

/**
 *
 * @author TEJSUMERU
 */
import javax.swing.*;
import java.awt.*;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Calculator implements ActionListener
{

    static JFrame main_window;
    static JTextField input_field;
    static JPanel panel;
    static GridLayout button_grid;
    static JButton bMode,bClear,bBackspace,bDivide,bMultiply,bMinus,bPlus,bEqual,b0,b1,b2,b3,b4,b5,b6,b7,b8,b9,bDot,bSqroot;

    public Calculator() 
    {
        createGUI();
    }
    
    public static void main(String args[])
    {
        Calculator cal = new Calculator();
        
        // Add Listeners For Button
        bMode.addActionListener(cal);
        bClear.addActionListener(cal);
        bBackspace.addActionListener(cal);
        bDivide.addActionListener(cal);
        bMultiply.addActionListener(cal);
        bMinus.addActionListener(cal);
        bPlus.addActionListener(cal);
        bEqual.addActionListener(cal);
        bDot.addActionListener(cal);
        bSqroot.addActionListener(cal);
        b0.addActionListener(cal);
        b1.addActionListener(cal);
        b2.addActionListener(cal);
        b3.addActionListener(cal);
        b4.addActionListener(cal);
        b5.addActionListener(cal);
        b6.addActionListener(cal);
        b7.addActionListener(cal);
        b8.addActionListener(cal);
        b9.addActionListener(cal);
    }

    void createGUI()
    {
        // Basic Frame Creation
        main_window = new JFrame("Calculator");
        main_window.setLayout(new FlowLayout());
        main_window.setSize(250,250);
        main_window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // Add TextField and Panel(Button Grid)
        input_field = new JTextField(18);
        input_field.setEditable(false);
        input_field.setPreferredSize(new Dimension(20,35));
        panel = new JPanel();
        button_grid = new GridLayout(5,4,2,2);

        // Creating Grid Of Buttons
        bMode = new JButton("%");
        bClear = new JButton("C");
        bBackspace = new JButton("⌫");
        bDivide = new JButton("÷");
        setDesign(bMode, Color.WHITE, Color.darkGray);
        setDesign(bClear, Color.WHITE, Color.RED);
        setDesign(bBackspace, Color.WHITE, Color.RED);
        setDesign(bDivide, Color.WHITE, Color.darkGray);
        
        b7 = new JButton("7");
        b8 = new JButton("8");
        b9 = new JButton("9");
        bMultiply = new JButton("X");
        setDesign(b7, Color.BLACK, Color.WHITE);
        setDesign(b8, Color.BLACK, Color.WHITE);
        setDesign(b9, Color.BLACK, Color.WHITE);
        setDesign(bMultiply, Color.WHITE, Color.darkGray);
        
        b4 = new JButton("4");
        b5 = new JButton("5");
        b6 = new JButton("6");
        bMinus = new JButton("-");
        setDesign(b4, Color.BLACK, Color.WHITE);
        setDesign(b5, Color.BLACK, Color.WHITE);
        setDesign(b6, Color.BLACK, Color.WHITE);
        setDesign(bMinus, Color.WHITE, Color.darkGray);
        
        b1 = new JButton("1");
        b2 = new JButton("2");
        b3 = new JButton("3");
        bPlus = new JButton("+");
        setDesign(b1, Color.BLACK, Color.WHITE);
        setDesign(b2, Color.BLACK, Color.WHITE);
        setDesign(b3, Color.BLACK, Color.WHITE);
        setDesign(bPlus, Color.WHITE, Color.darkGray);
        
        bSqroot = new JButton("√");
        b0 = new JButton("0");    
        bDot = new JButton(".");
        bEqual = new JButton("=");
        setDesign(b0, Color.BLACK, Color.WHITE);
        setDesign(bSqroot, Color.WHITE, Color.darkGray);
        setDesign(bDot, Color.BLACK, Color.WHITE);
        setDesign(bEqual, Color.WHITE, Color.RED);

        // Add Field And Panel
        main_window.add(input_field);
        panel.setLayout(button_grid);
        
        // Add Buttons Into Panel
        panel.add(bClear);
        panel.add(bBackspace);
        panel.add(bMode);
        panel.add(bDivide);
        
        panel.add(b7);
        panel.add(b8);
        panel.add(b9);
        panel.add(bMultiply);
        
        panel.add(b4);
        panel.add(b5);
        panel.add(b6);
        panel.add(bMinus);
        
        panel.add(b1);
        panel.add(b2);
        panel.add(b3);
        panel.add(bPlus);
        
        panel.add(bDot);
        panel.add(b0);
        panel.add(bEqual);    
        panel.add(bSqroot);
        
        main_window.add(panel);
        main_window.setBackground(Color.GRAY);
        main_window.setVisible(true);
    }
    
    void setDesign(JButton button,Color foreground,Color background)
    {
        button.setBackground(background);
        button.setForeground(foreground);
    }

    @Override
    public void actionPerformed(ActionEvent e) 
    {
        String key_Info = e.getActionCommand();
        
        if (key_Info.equals("C"))
        {
            input_field.setText("");
        }
        else if (key_Info.equals("="))
        {
            String output = evaluate(input_field.getText());
            input_field.setText(output);
        }
        else if (key_Info.equals("⌫"))
        {
            String current = input_field.getText();
            input_field.setText(current.substring(0,current.length()-1));
        }
        else
        {
            input_field.setText(input_field.getText() + key_Info);
        }
    }
    
    String evaluate(String expression)
    {
        char[] exp_char = expression.toCharArray();
        String op1="",op2="",operator="";
        double result=0;
        
        for(int i=0;i<exp_char.length;i++)
        {
            if ((exp_char[i]>='0' && exp_char[i]<='9') || exp_char[i]=='.')
            {
                if (operator.isEmpty())
                {
                    op1 = op1 + exp_char[i];
                }
                else
                {
                    op2 = op2 + exp_char[i];
                }
            }
            
            if (exp_char[i]=='+' || exp_char[i]=='-' || exp_char[i]=='X' || exp_char[i]=='÷' || exp_char[i]=='%' || exp_char[i]=='√')
            {
                operator = operator + exp_char[i];
            }
        }
        
        if (operator.equals("+"))
         result = (Double.parseDouble(op1) + Double.parseDouble(op2));
        else if (operator.equals("-"))
         result = (Double.parseDouble(op1) - Double.parseDouble(op2));
        else if (operator.equals("X"))
         result = (Double.parseDouble(op1) * Double.parseDouble(op2));
        else if (operator.equals("÷"))
         result = (Double.parseDouble(op1) / Double.parseDouble(op2));
        else if (operator.equals("%"))
         result = (Double.parseDouble(op1) % Double.parseDouble(op2));
        else if (operator.equals("√"))
         result = Math.sqrt(Double.parseDouble(op2));
        else
            return "Invalid Syntax";
        
        return String.valueOf(result);
    }
}

Design Explanation

When we first create the object of the Calculator class, it will call it’s constructor. Inside Constructor the method createGUI() is called which is used to create basic UI of the Calculator.

After creating the createGUI() method, we first create the frame using JFrame Class inside this method. For this frame we set the layout as a FlowLayout using setLayout() method. In FlowLayout we will ad one textfield and one panel. Panel is used to create grid of buttons. We will add these JTextField and JPanel into the JFrame. JPanel is used GridLayout, which will have JButton inside it.

We can change the background of the button using the setBackground() method. We can change font color using the method setForeground(). In this we have created one method called setDesign() which will take object of button, Color constant for background and foreground.

ActionListener Explanation

Now, we have to implement the ActionListener that perform the operation on button click. After implementing the ActionListener, override it’s method actionPerformed(ActionEvent e) and then add this listener for all buttons using the addActionListener(current_object_context).

Inside the actionPerformed() method, first we have to get the value of the button which is pressed. For this we can use getActionCommand() which is part of ActionEvent class.

Evaluate Expression

In calculator, we are having four unique operation. That unique keys are Clear(C), Equals(=), Backspace(<-) and appending pressed key into TextField. So, we are checking the pressed key and perform operation based on that.

The pressed key is C, then we have to clear the TextField, so we use setText(“”).

And If the pressed key is Backspace, then we have to remove the last character from the entered string so we are using substring function for this.

If the pressed key is = then we have to evaluate the entered expression. For that we have created one method called evaluate(String str), that takes string of expression and evaluate it.

Inside evaluate() method, we are using three variable op1,op2 and operator. After that we iterate the loop for entire string, and checking that if value of operand is null than we append the character in op1 else in op2. At last we evaluate the expression based on operator using switch case.

If the pressed key is not from any of the above, we simply append that key value in TextField.

That’s it. The Calculator is working fine, you can now execute it.

Leave a Reply

Your email address will not be published.