swing

Java Calculator using Swing Example

Swing is a GUI widget toolkit for Java. It is part of Oracle’s Java Foundation Classes (JFC) – an API for providing a graphical user interface (GUI) for Java programs. Swing was developed to provide a more sophisticated set of GUI components than the earlier Abstract Window Toolkit (AWT). JAVA provides a rich set of libraries to create Graphical User Interface in platform independent way. So lets see how to create a calculator in java.

1. Introduction

Swing API is set of extensible GUI Components to ease developer’s life to create JAVA based Front End/ GUI Applications. It is build upon top of AWT API and acts as replacement of AWT API as it has almost every control corresponding to AWT controls. Swing component follows a Model-View-Controller architecture to fulfill the following criteria.

  • A single API is to be sufficient to support multiple look and feel.
  • API is to model driven so that highest level API is not required to have the data.
  • API is to use the Java Bean model so that Builder Tools and IDE can provide better services to the developers to use it.

2. JAVA Swing

Unlike AWT, Java Swing provides platform-independent and lightweight components. The javax.swing package provides classes for java swing API such as JButton, JTextField, JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.

2.1 MVC Architecture

Swing API architecture follows loosely based MVC architecture in the following manner.

  • A Model represents component’s data.
  • View represents visual representation of the component’s data.
  • Controller takes the input from the user on the view and reflects the changes in Component’s data.
  • Swing component have Model as a separate element and View and Controller part are clubbed in User Interface elements. Using this way, Swing has pluggable look-and-feel architecture.

Every user interface considers the following three main aspects:

  • UI elements : These are the core visual elements the user eventually sees and interacts with. GWT provides a huge list of widely used and common elements varying from basic to complex.
  • Layouts: They define how UI elements should be organized on the screen and provide a final look and feel to the GUI (Graphical User Interface).
  • Behavior: These are events which occur when the user interacts with UI elements.

2.2 Swing Features

  • Light Weight – Swing component are independent of native Operating System’s API as Swing API controls are rendered mostly using pure JAVA code instead of underlying operating system calls.
  • Rich controls – Swing provides a rich set of advanced controls like Tree, TabbedPane, slider, colorpicker, table controls.
  • Highly Customizable – Swing controls can be customized in very easy way as visual apperance is independent of internal representation.
  • Pluggable look-and-feel– SWING based GUI Application look and feel can be changed at run time based on available values.

2.3 Setup

Popular Java Editors:
To write your java programs you will need a text editor. There are even more sophisticated IDE available in the market. But for now, you can consider one of the following:

  • Notepad: On Windows machine you can use any simple text editor like Notepad TextPad.
  • NetBeans: is a Java IDE that is open source and free which can be downloaded from http://www.netbeans.org/index.html.
  • Eclipse: is also a java IDE developed by the eclipse open source community and can be downloaded from http://www.eclipse.org

2.4 Class and description

  • Component: A Component is the abstract base class for the non menu user-interface controls of SWING. Component represents an object with graphical representation.
  • Container: A Container is a component that can contain other SWING components.
  • JComponent: A JComponent is a base class for all swing UI components. In order to use a swing component that inherits from JComponent, component must be in a containment hierarchy whose root is a top-level Swing container.

3. Swing Java Calculator Example

This tutorial is about how to make a calculator in Java. Below I have shared the simple calculator program in java using swing. It is a simple calculator in Java which can perform basic arithmetic operations.

Calculator.java

import java.awt.*;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JTextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Calculator extends JFrame implements ActionListener
{
    JButton addButton,b0,b1,b2,b3,b4,b5,b6,b7,b8,b9,BACKSPACE,CE,C,MC,div,sqrt,MR,mul,per,MS,sub,prop,M,pm,dot,eq;
    JTextField mainTextField, memoryTextField;
    double result=0,memory=0,n1=0;

    //Mark the first number for easy calculation
    int first=1;

    //First number for percentage calculation
    double num;

    //Flag for appending digits or starting a new number
    /*1->Appending a digit to the existing number
      2->Taking a new number as input*/
    int opt=2;

    //Flag to mark binary operation for '=' button
    /*0->No Operation
      1->Addtion
      2->Subtraction
      3->Division
      4->Multiplication*/
    int oper1=0,oper2=0;

    Calculator()
    {
        setTitle("Calculator");
        setSize(300,300);
        setResizable(false);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        initComponents();
    }
    //Function for creating User Interface
    void initComponents()
    {
        mainTextField = new JTextField(32);
        mainTextField.setText("0");
        add(mainTextField,BorderLayout.NORTH);
        mainTextField.setHorizontalAlignment(JTextField.RIGHT);
        JPanel panel7 = new JPanel();

        //Panel 1
        JPanel panel1 = new JPanel();

        memoryTextField = new JTextField(5);
        memoryTextField.setText(" ");
        panel1.add(memoryTextField);
        MC = new JButton("MC");
        MC.setForeground(Color.BLACK);
        panel1.add(MC);
        MR = new JButton("MR");
        MR.setForeground(Color.BLACK);
        panel1.add(MR);
        M = new JButton("M+");
        M.setForeground(Color.BLACK);
        panel1.add(M);
        MS = new JButton("MS");
        MS.setForeground(Color.BLACK);
        panel1.add(MS);

        panel7.add(panel1);

        //Panel 2
        JPanel panel2 = new JPanel();

        CE= new JButton("CE");
        CE.setForeground(Color.BLACK);
        panel2.add(CE);
        C = new JButton("C");
        panel2.add(C);
        C.setForeground(Color.BLACK);
        BACKSPACE = new JButton("BACKSPACE");
        BACKSPACE.setForeground(Color.BLACK);
        panel2.add(BACKSPACE);
        sqrt = new JButton("sqrt");
        sqrt.setForeground(Color.BLUE);
        panel2.add(sqrt);

        panel7.add(panel2);

        //Panel 3
        JPanel panel3 = new JPanel();

        b7 = new JButton("7");
        b7.setForeground(Color.BLUE);
        panel3.add(b7);
        b8= new JButton("8");
        b8.setForeground(Color.BLUE);
        panel3.add(b8);
        b9 = new JButton("9");
        b9.setForeground(Color.BLUE);
        panel3.add(b9);
        div = new JButton("/");
        div.setForeground(Color.BLACK);
        panel3.add(div);
        per = new JButton("%");
        per.setForeground(Color.BLUE);
        panel3.add(per);

        panel7.add(panel3);

        //Panel 4
        JPanel panel4 = new JPanel();

        b4= new JButton("4");
        b4.setForeground(Color.BLUE);
        panel4.add(b4);
        b5 = new JButton("5");
        b5.setForeground(Color.BLUE);
        panel4.add(b5);
        b6= new JButton("6");
        b6.setForeground(Color.BLUE);
        panel4.add(b6);
        mul = new JButton("*");
        mul.setForeground(Color.BLACK);
        panel4.add(mul);
        prop = new JButton("1/x");
        prop.setForeground(Color.BLUE);
        panel4.add(prop);

        panel7.add(panel4);

        //Panel 5
        JPanel panel5 = new JPanel();

        b1 = new JButton("1");
        b1.setForeground(Color.BLUE);
        panel5.add(b1);
        b2= new JButton("2");
        b2.setForeground(Color.BLUE);
        panel5.add(b2);
        b3 = new JButton("3");
        b3.setForeground(Color.BLUE);
        panel5.add(b3);
        sub = new JButton("-");
        sub.setForeground(Color.BLACK);
        panel5.add(sub);
        pm= new JButton("+/-");
        pm.setForeground(Color.BLUE);
        panel5.add(pm);

        panel7.add(panel5);

        //Panel 6
        JPanel panel6 = new JPanel();

        b0= new JButton("0");
        b0.setForeground(Color.BLUE);
        panel6.add(b0);
        dot= new JButton(".");
        dot.setForeground(Color.BLUE);
        panel6.add(dot);
        addButton = new JButton("+");
        addButton.setForeground(Color.BLACK);
        panel6.add(addButton);
        eq = new JButton("=");
        eq.setForeground(Color.BLACK);
        panel6.add(eq);

        panel7.add(panel6);

        panel1.setBackground(Color.blue);
        panel7.setBackground(Color.LIGHT_GRAY);

        //Adding all individual panels to main panel7
        add(panel7,BorderLayout.CENTER);

        //Add events
        addButton.addActionListener(this);
        b0.addActionListener(this);
        b1.addActionListener(this);
        b2.addActionListener(this);
        b3.addActionListener(this);
        b4.addActionListener(this);
        b5.addActionListener(this);
        b6.addActionListener(this);
        b7.addActionListener(this);
        b8.addActionListener(this);
        b9.addActionListener(this);
        BACKSPACE.addActionListener(this);
        CE.addActionListener(this);
        C.addActionListener(this);
        MC.addActionListener(this);
        div.addActionListener(this);
        sqrt.addActionListener(this);
        MR.addActionListener(this);
        mul.addActionListener(this);
        per.addActionListener(this);
        MS.addActionListener(this);
        sub.addActionListener(this);
        prop.addActionListener(this);
        M.addActionListener(this);
        pm.addActionListener(this);
        dot.addActionListener(this);
        eq.addActionListener(this);
        per.addActionListener(this);
    }

    //Method when ActionListener calls its corresponding routine
    public void actionPerformed(ActionEvent evt)
    {
        String str;

        //Action Corresponding to + button
        if(evt.getSource()== addButton)
        {
            if(first==1)
            {
                result=num=Double.parseDouble(mainTextField.getText());
                oper1=1;
            }
            else
            {
                n1=Double.parseDouble(mainTextField.getText());
                oper2=1;
            }

            //Action corresponding to previous operator
            switch(oper1)
            {
                case 1:add1();
                    break;
                case 2:sub();
                    break;
                case 3:div();
                    break;
                case 4:mul();
                    break;
            }
        }

        //Action Corresponding to * button
        if(evt.getSource()==mul)
        {
            if(first==1)
            {
                result=num=Double.parseDouble(mainTextField.getText());
                oper1=4;
            }
            else
            {
                n1=Double.parseDouble(mainTextField.getText());
                oper2=4;
            }

            //Action corresponding to previous operator
            switch(oper1)
            {
                case 1:add1();
                    break;
                case 2:sub();
                    break;
                case 3:div();
                    break;
                case 4:mul();
                    break;
            }
        }

        //Action Corresponding to / button
        if(evt.getSource()==div)
        {
            if(first==1)
            {
                result=num=Double.parseDouble(mainTextField.getText());
                oper1=3;
            }
            else
            {
                n1=Double.parseDouble(mainTextField.getText());
                oper2=3;
            }

            //Action corresponding to previous operator
            switch(oper1)
            {
                case 1:add1();
                    break;
                case 2:sub();
                    break;
                case 3:div();
                    break;
                case 4:mul();
                    break;
            }
        }

        //Action Corresponding to - button
        else if(evt.getSource()==sub)
        {
            if(first==1)
            {
                result=num=Double.parseDouble(mainTextField.getText());
                oper1=2;
            }
            else
            {
                n1=Double.parseDouble(mainTextField.getText());
                oper2=2;
            }

            //Action corresponding to previous operator
            switch(oper1)
            {
                case 1:add1();
                    break;
                case 2:sub();
                    break;
                case 3:div();
                    break;
                case 4:mul();
                    break;
            }

        }

        //Action Corresponding to = button
        else if(evt.getSource()==eq)
        {
            double n1=Double.parseDouble(mainTextField.getText());
            if(oper1==1)
                result=result+n1;
            else if(oper1==2)
                result=result-n1;
            else if(oper1==3)
                result=result/n1;
            else if(oper1==4)
                result=result*n1;
            else
                result=Double.parseDouble(mainTextField.getText());
            num=result;
            str=String.valueOf(result);
            mainTextField.setText(str);
        }

        //Action Corresponding to MS button
        else if(evt.getSource()==MS)
        {
            memory=Double.parseDouble(mainTextField.getText());
            str=String.valueOf("M");
            memoryTextField.setText(str);

        }

        //Action Corresponding to M button
        else if(evt.getSource()==M)
        {
            memory=memory+Double.parseDouble(mainTextField.getText());
        }

        //Action Corresponding to MC button
        else if(evt.getSource()==MC)
        {
            memory=0;
            mainTextField.setText("0");
            memoryTextField.setText(" ");
        }

        //Action Corresponding to MR button
        else if(evt.getSource()==MR)
        {
            str=String.valueOf(memory);
            mainTextField.setText(str);
        }

        //Action Corresponding to +/- button
        else if(evt.getSource()==pm)
        {
            double n1=Double.parseDouble(mainTextField.getText());
            n1=-n1;
            str=String.valueOf(n1);
            mainTextField.setText(str);
        }

        //Action Corresponding to 0 button
        else if(evt.getSource()==b0)
        {
            if(opt==1)
                str=String.valueOf(mainTextField.getText())+0;
            else
                str=String.valueOf(" ")+0;
            opt=1;
            mainTextField.setText(str);

        }

        //Action Corresponding to 1 button
        else if(evt.getSource()==b1)
        {
            if(opt==1)
                str=String.valueOf(mainTextField.getText())+1;
            else
                str=String.valueOf(" ")+1;
            opt=1;
            mainTextField.setText(str);

        }

        //Action Corresponding to 2 button
        else if(evt.getSource()==b2)
        {
            if(opt==1)
                str=String.valueOf(mainTextField.getText())+2;
            else
                str=String.valueOf(" ")+2;
            opt=1;
            mainTextField.setText(str);
        }

        //Action Corresponding to 3 button
        else if(evt.getSource()==b3)
        {
            if(opt==1)
                str=String.valueOf(mainTextField.getText())+3;
            else
                str=String.valueOf(" ")+3;
            opt=1;
            mainTextField.setText(str);
        }

        //Action Corresponding to 4 button
        else if(evt.getSource()==b4)
        {
            if(opt==1)
                str=String.valueOf(mainTextField.getText())+4;
            else
                str=String.valueOf(" ")+4;
            opt=1;
            mainTextField.setText(str);
        }

        //Action Corresponding to 5 button
        else if(evt.getSource()==b5)
        {
            if(opt==1)
                str=String.valueOf(mainTextField.getText())+5;
            else
                str=String.valueOf(" ")+5;
            opt=1;
            mainTextField.setText(str);
        }

        //Action Corresponding to 6 button
        else if(evt.getSource()==b6)
        {
            if(opt==1)
                str=String.valueOf(mainTextField.getText())+6;
            else
                str=String.valueOf(" ")+6;
            opt=1;
            mainTextField.setText(str);
        }

        //Action Corresponding to 7 button
        else if(evt.getSource()==b7)
        {
            if(opt==1)
                str=String.valueOf(mainTextField.getText())+7;
            else
                str=String.valueOf(" ")+7;
            opt=1;
            mainTextField.setText(str);
        }

        //Action Corresponding to 8 button
        else if(evt.getSource()==b8)
        {
            if(opt==1)
                str=String.valueOf(mainTextField.getText())+8;
            else
                str=String.valueOf(" ")+8;
            opt=1;
            mainTextField.setText(str);
        }

        //Action Corresponding to 9 button
        else if(evt.getSource()==b9)
        {
            if(opt==1)
                str=String.valueOf(mainTextField.getText())+9;
            else
                str=String.valueOf(" ")+9;
            opt=1;
            mainTextField.setText(str);
        }

        //Action Corresponding to BACKSPACE button
        else if(evt.getSource()==BACKSPACE)
        {
            int len;
            str= mainTextField.getText();
            len=str.length();
            if(len>=1)
                str=str.substring(0,len-1);
            mainTextField.setText(str);
        }

        //Action Corresponding to CE button
        else if(evt.getSource()==CE)
        {
            result=0;
            first=1;
            opt=2;
            str=String.valueOf('0');
            mainTextField.setText(str);

        }

        //Action Corresponding to C button
        else if(evt.getSource()==C)
        {
            result=0;
            memory=0;
            first=1;
            opt=2;
            mainTextField.setText("0");
            memoryTextField.setText(" ");

        }

        //Action Corresponding to . button
        else if(evt.getSource()==dot)
        {
            str=String.valueOf(mainTextField.getText())+".";
            mainTextField.setText(str);
        }

        //Action Corresponding to 1/x button
        else if(evt.getSource()==prop)
        {
            double n1=Double.parseDouble(mainTextField.getText());
            n1=1/n1;
            str=String.valueOf(n1);
            mainTextField.setText(str);
        }

        //Action Corresponding to sqrt button
        else if(evt.getSource()==sqrt)
        {
            double n1=Double.parseDouble(mainTextField.getText());
            n1=Math.sqrt(n1);
            str=String.valueOf(n1);
            mainTextField.setText(str);
        }

        //Action Corresponding to % button
        else if(evt.getSource()==per)
        {
            double n1=Double.parseDouble(mainTextField.getText());
            n1=(n1*num)/100;
            str=String.valueOf(n1);
            mainTextField.setText(str);
        }

    }

    //Add called according to previous operator
    void add1()
    {
        if(first==0)
            result=num=result+n1;
        String str=String.valueOf(result);
        mainTextField.setText(str);
        opt=2;
        if(oper2!=0)
        {
            oper1=oper2;
            oper2=0;
        }
        first=0;
    }

    //Sub called according to previous operator
    void sub()
    {
        if(first==0)
            result=num=result-n1;
        String str=String.valueOf(result);
        mainTextField.setText(str);
        opt=2;
        if(oper2!=0)
            oper1=oper2;
        first=0;
    }

    //Div called according to previous operator
    void div()
    {
        if(first==0)
        {
            if(n1==0)
                mainTextField.setText("Cannot divide by zero");
            else
                result=num=result/n1;
        }
        String str=String.valueOf(result);
        mainTextField.setText(str);
        opt=2;
        if(oper2!=0)
            oper1=oper2;
        first=0;
    }

    //Mul called according to previous operator
    void mul()
    {
        if(first==0)
            result=num=result*n1;
        String str=String.valueOf(result);
        mainTextField.setText(str);
        opt=2;
        if(oper2!=0)
            oper1=oper2;
        first=0;
    }
    public static void main(String args[])
    {
        Calculator obj = new Calculator();
        obj.setVisible(true);
    }
}

3.1 Output

Output of code will be like the one below.

Java Calculator - Calculator result
Calculator result

3.2 Different keys usage:

Here are the keys used in this calculator:

  • MC = Memory Clear sets the memory to 0
  • MR = Memory Recall uses the number in memory
  • MS = Memory Store puts the number on the display into the memory
  • M+ = Memory Add takes the number on the display, adds it to the memory, and puts the result into memory

In the program as you see I’ve added buttons onto panels and used 2 textfields:

  • mainTextField for integer calculation
  • memoryTextField for marking memory operations.

Method of calculating in calculator has been kept simple as Standard Microsoft Calculators.

Event Handling has been used where a source generates an event and a listener is notified  when an event occurs say when a button is pressed using a mouse.

4. Download the Source Code

This was an example of java calculator example.

Download
You can download the full source code of this example here: Java Calculator using Swing Example

Last updated on Sept. 29, 2019

Jyoti Jha

Jyoti is a tech enthusiast and is an avid programmer. She holds a post graduation degree in (M.Tech) Computer Science Engineering from Thapar Univeristy, Patiala, India. Post her graduate studies, she has worked in Software companies such as SLK Software and Aricent, India as Software Engineer in various projects primarily in the field of Requirement analysis and design, implementing new algorithms in C++ and JAVA used in ISDN network and designing databases and. She is inquisitive about socio economic reforms as well as advancement in technical fronts and keep herself informed with TED talks and various blogs.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
George Taylor, IV
George Taylor, IV
5 years ago

line 118 change OperatorAction(1) to OperatorAction(action) to make it work.

Back to top button