Home » Desktop Java » swing » Java Calculator using Swing Example

About Jyoti Jha

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.

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.

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

Prerequisite
This example is developed on Eclipse therefore a compatible Eclipse IDE is required to be installed on the system.
We also need WindowBuilder tool to be installed on Eclipse IDE for the easiness of the work. To learn how to install WindowBuilder tool please visit the Setup section 2.1 of the following link click here.

2.4 Creating Menus

The following code creates the menus shown near the beginning of this menu section. Because this code has no event handling, the menus do nothing useful except to look as they should. If you run the example, you’ll notice that despite the lack of custom event handling, menus and submenus appear when they should, and the check boxes and radio buttons respond appropriately when the user chooses them.

2.5 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 like addition, subtraction, multiplication and division of two numbers.

JavaCalculator.java

001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
package swing_1;
 
//The java Template Calculator TODO
 
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.Container;
 
public class JavaCalculator implements ActionListener{
 
JFrame guiFrame;
JPanel buttonPanel;
JTextField numberCalc;
int calcOperation = 0;
int currentCalc;
 
public static void main(String[] args) {
 
   EventQueue.invokeLater(new Runnable()
   {
 
       public void run()
       {
 
           new JavaCalculator();        
       }
   });
 
}
 
public JavaCalculator()
{
  guiFrame = new JFrame();
  guiFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  guiFrame.setTitle("Simple Calculator");
  guiFrame.setSize(300,300);
  guiFrame.setLocationRelativeTo(null);
  numberCalc = new JTextField();
  numberCalc.setHorizontalAlignment(JTextField.RIGHT);
  numberCalc.setEditable(false);
  guiFrame.add(numberCalc, BorderLayout.NORTH);
  buttonPanel = new JPanel();
  buttonPanel.setLayout(new GridLayout(4,4));  
  guiFrame.add(buttonPanel, BorderLayout.CENTER);
 
  for (int i=0;i<10;i++)
  {
      addNumberButton(buttonPanel, String.valueOf(i));
  }
 
  addActionButton(buttonPanel, 1, "+");
  addActionButton(buttonPanel, 2, "-");
  addActionButton(buttonPanel, 3, "*");
  addActionButton(buttonPanel, 4, "/");
  addActionButton(buttonPanel, 5, "^2");
 
  JButton equalsButton = new JButton("=");
  equalsButton.setActionCommand("=");
  equalsButton.addActionListener(new ActionListener()
  {
      public void actionPerformed(ActionEvent event)
      {
          if (!numberCalc.getText().isEmpty())
          {
              int number = Integer.parseInt(numberCalc.getText());
              if (calcOperation == 1)
              {
                  int calculate = currentCalc  + number;
                  numberCalc.setText(Integer.toString(calculate));
              }
              else if (calcOperation == 2)
              {
                  int calculate = currentCalc  - number;
                  numberCalc.setText(Integer.toString(calculate));
              }
              else if (calcOperation == 3)
              {
                  int calculate = currentCalc  * number;
                  numberCalc.setText(Integer.toString(calculate));
              }
              else if (calcOperation == 4)
              {
                  int calculate = currentCalc  / number;
                  numberCalc.setText(Integer.toString(calculate));
              }
              else if (calcOperation == 5)
              {
                  int calculate = currentCalc  * currentCalc;
                  numberCalc.setText(Integer.toString(calculate));
              }
          }
      }
  });
 
  buttonPanel.add(equalsButton);
  guiFrame.setVisible(true); 
}
 
private void addNumberButton(Container parent, String name)
{
  JButton but = new JButton(name);
  but.setActionCommand(name);
  but.addActionListener(this);
  parent.add(but);
}
 
private void addActionButton(Container parent, int action, String text)
{
  JButton but = new JButton(text);
  but.setActionCommand(text);
  OperatorAction addAction = new OperatorAction(1);
  but.addActionListener(addAction);
  parent.add(but);
}
 
public void actionPerformed(ActionEvent event)
{
  String action = event.getActionCommand();
 
  numberCalc.setText(action);      
}
 
private class OperatorAction implements ActionListener
{
  private int operator;
 
  public OperatorAction(int operation)
  {
      operator = operation;
  }
 
  public void actionPerformed(ActionEvent event)
  {
      currentCalc = Integer.parseInt(numberCalc.getText());
      calcOperation = operator;
  }
}
}

3.1 Output

Output of code will be like the one below.

Java Calculator
Java Calculator

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
(No Ratings Yet)
1 Comment Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

1
Leave a Reply

avatar
1 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
George Taylor, IV Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
George Taylor, IV
Guest
George Taylor, IV

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