Create your first GUI Calculator (JAVA Swing)

Create your first GUI Calculator (JAVA Swing)

It can perform basic arithmetic operations

·

6 min read

In this article, we will learn how to create a GUI (Graphical User Interface) calculator using the light weight Components of JAVA Swing and AWT Event Handling mechanism which can perform basic arithmetic operations like addition, subtraction, division and multiplication.

Prerequisites:

  1. OOPs Concepts
  2. JAVA

Requirements:

  1. Latest version of JDK must be installed and path should be added to Environment Variables, so that it can be accessed globally
  2. Any Java IDE (like IntelliJ IDEA, Eclipse) or Light Weight Text Editor (like Sublime, VS Code)

Preview of this project

sum.jpg

Let's get started

Every event classes have their corresponding listener interfaces. A class wishing to listen and respond to a button click event which is an object of type ActionEvent, must implement ActionListener interface. Therefore, we need to import all the dependencies (java packages) before using them in the program further.

import javax.swing.*;
import java.awt.event.*;

As Java is an Object Oriented Programming language. We first need to create a class that extends JFrame class (single-level inheritance) and implements ActionListener interface, so that it can listen and respond to ActionEvent class and a public constructor for initialization of object.

import javax.swing.*;
import java.awt.event.*;

class SwingGUI extends JFrame implements ActionListener {

      public SwingGUI() {

      }
}

Anatomy of UI

anatomy.jpg

In the above image, we can see that several different components like Labels, TextFields and Buttons are used in UI. There are two text fields for taking user input which can be created using the object of JTextField. JTextField(int columns) constructor creates a new empty text field with specified number of columns. Also there are three JLabel and four JButton. All those components classes are present in the javax.swing package.

So, in order to use these components, we must create objects of those respective component classes as follows:

import javax.swing.*;
import java.awt.event.*;

class SwingGUI extends JFrame implements ActionListener {
    JTextField t1, t2;
    JLabel lb1, lb2, lb3;
    JButton sum_btn, sub_btn, mul_btn, div_btn;

      public SwingGUI() {

      }
}

For setting a title or name of this application in the title bar, we need the constructor JFrame(String title) which sets the specified title. In order to invoke the parent class constructor from the extended or derived class, we need to use:

super("BASIC CALCULATOR");

title-bar.jpg

import javax.swing.*;
import java.awt.event.*;

class SwingGUI extends JFrame implements ActionListener {
    JTextField t1, t2;
    JLabel lb1, lb2, lb3;
    JButton sum_btn, sub_btn, mul_btn, div_btn;

      public SwingGUI() {
        super("BASIC CALCULATOR");
      }
}

By default, the JPanel has a FlowLayout manager. The layout manager is used to place widgets onto the containers. If we call setLayout(null) we can position our components absolutely which gives more flexibility.

In order to set the size of window we have to use setSize(width, height) method which makes a rectangular area of given "width" px by "height" px.

The setVisible(true) method makes the frame appear on the screen.

The setDefaultCloseOperation() method is used to specify one of several options for the close button. We can use one of the following constants to specify your choice:

  • JFrame.EXIT_ON_CLOSE - Exit the application.
  • JFrame.HIDE_ON_CLOSE - Hide the frame, but keep the application running.
  • JFrame.DISPOSE_ON_CLOSE - Dispose off the frame object, but keep the application running.
  • JFrame.DO_NOTHING_ON_CLOSE - Ignore the click.

If we forget to call setDefaultCloseOperation() we will get JFrame.HIDE_ON_CLOSE by default. This can be frustrating, because it looks like we have "killed" the program, but it keeps on running, and we see no frame.

import javax.swing.*;
import java.awt.event.*;

class SwingGUI extends JFrame implements ActionListener {
    JTextField t1, t2;
    JLabel lb1, lb2, lb3;
    JButton sum_btn, sub_btn, mul_btn, div_btn;

      public SwingGUI() {
        super("BASIC CALCULATOR");


        setLayout(null);
        setSize(600,400);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      }
}

Now, we will initialize the instances for every classes. Furthermore, we will use setBounds(int x-coordinate, int y-coordinate, int width, int height) and add() methods to specify the width, height, position of every individual components and add them in the user interface respectively.

The common way to implement the ActionListener is to register the components (Buttons) using component.addActionListener(instanceOfListenerclass); method.

The actionPerformed() method is invoked automatically whenever we click on the registered component.

import javax.swing.*;
import java.awt.event.*;

class SwingGUI extends JFrame implements ActionListener {
    JTextField t1, t2;
    JLabel lb1, lb2, lb3;
    JButton sum_btn, sub_btn, mul_btn, div_btn;

      public SwingGUI() {
        super("BASIC CALCULATOR");
        lb1 = new JLabel("Enter First Number:  ");
        lb1.setBounds(90,20,150,30);
        add(lb1);

        t1 = new JTextField(30);
        t1.setBounds(90,50,150,30);
        add(t1);

        lb2 = new JLabel("Enter Second Number:  ");
        lb2.setBounds(90,80,150,30);
        add(lb2);

        t2 = new JTextField(30);
        t2.setBounds(90,110,150,30);
        add(t2);

        lb3 = new JLabel("Result:  ");
        lb3.setBounds(90,160,250,30);
        add(lb3);

        sum_btn = new JButton(" + ");
        sum_btn.setBounds(90,200,50,30);
        add(sum_btn);
        sum_btn.addActionListener(this);

        sub_btn = new JButton(" - ");
        sub_btn.setBounds(160,200,50,30);
        add(sub_btn);
        sub_btn.addActionListener(this);

        mul_btn = new JButton(" * ");
        mul_btn.setBounds(230,200,50,30);
        add(mul_btn);
        mul_btn.addActionListener(this);

        div_btn = new JButton(" / ");
        div_btn.setBounds(300,200,50,30);
        add(div_btn);
        div_btn.addActionListener(this);


        setLayout(null);
        setSize(600,400);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      }

@Override
    public void actionPerformed(ActionEvent e) {

    if(e.getSource().equals(sum_btn)) {
        int  a = Integer.parseInt(t1.getText());
        int  b = Integer.parseInt(t2.getText());
        int sum = a + b;
        lb3.setText("Result:  "+a+" + "+b+" = "+String.valueOf(sum));
    }

        else if(e.getSource().equals(sub_btn)) {
        int  a = Integer.parseInt(t1.getText());
        int  b = Integer.parseInt(t2.getText());
        int sub = a - b;
        lb3.setText("Result:  "+a+" - "+b+" = "+String.valueOf(sub));
    }

        else if(e.getSource().equals(mul_btn)) {
        int  a = Integer.parseInt(t1.getText());
        int  b = Integer.parseInt(t2.getText());
        int mul = a * b;
        lb3.setText("Result:  "+a+" * "+b+" = "+String.valueOf(mul));
    }

        else if(e.getSource().equals(div_btn)) {
        int  a = Integer.parseInt(t1.getText());
        int  b = Integer.parseInt(t2.getText());
        double div = a / (b*1.0);
        lb3.setText("Result:  "+a+" / "+b+" = "+String.valueOf(div));
    }
}

public static void main(String[] args) {
        SwingGUI gui = new SwingGUI();
    }
}

The getSource() method is used in the actionPerformed() method to determine which button was clicked. It returns the object on which the event occurred.

The setText() method of java.text.StringCharacterIterator class in Java is used to set the current text that is to be read by this StringCharacterIterator. This method takes the text to be set as a parameter and sets the text of this StringCharacterIterator at JLabel.

String.valueOf() method converts different types of values into string. By the help of String.valueOf() method, we can convert int, long, boolean, character, float, double, object and char array to String.

As all the inputs given in the JTextField are of type String, to perform any mathematical operations, we need to convert these strings to int. We can accomplish this task using Integer.parseInt(String s) method which parses the string argument as a signed decimal integer.

The main() method is required because the compiler starts executing a program from this entry point. The JVM needs to instantiate the class if the main() method is allowed to be non-static. JVM can call the static methods easily without creating an instance of the class by using the class name only.

How to compile and run ?

We can follow normal process for the compilation and execution using Command Prompt(CMD) as follows:

running.jpg

Output:

run.jpg

div.jpg

mul.jpg

Congratulations for your first mini GUI project. Keep learning and have fun!! ✨

Download Source Code from GitHub

Did you find this article valuable?

Support Anuj Das by becoming a sponsor. Any amount is appreciated!