Spread the love

How to Create Calculator in Swing in Java

Spread the love

Objective of this Approach:

In my last few posts I have told you about how to write code for a calculator using Applet.
In my last posts I have shown

these posts are based on AWT.
In this post I will show you how to create a calculator using Swing.
We will see…

  • How to add button using swing
  • How to create text box using swing
  • How to mix swing with AWT components
  • How to use AWT layout
  • How to use action listener 
Basic Requirements:

The requirements are ..

  • There will be buttons with number 1 to 9
  • There will be simple arithmetic operation button like-‘+’,’-‘,’*’ and ‘/’
  • There will an equal(‘=’) button
  • The resultant will be displayed in a text box.
How to Code:

Let me show you step by step guide to set up calculator using Swing

This piece of code will populate the calculator frame in the mid of screen..Toolkit class will help us to get the screen size. We will use this to set the position of the calculator which will appear.

Toolkit tk = Toolkit.getDefaultToolkit();
Dimension screenSize = tk.getScreenSize();
final int WIDTH = screenSize.width;
final int HEIGHT = screenSize.height;
frame.setLocation(WIDTH / 4, WIDTH / 4);

In my last post I have shown how array of buttons works…I will use the same concept to add button. But now with a new way to create button. Hope you will like it.

String buttonOrder = "1234567890 ";
for (int i = 0; i < buttonOrder.length(); i++) {
String key = buttonOrder.substring(i, i+1);
//this will determine the key
if (key.equals(" ")) {
buttonPanel.add(new JLabel(""));
}
else {
//This section will create button,add action listener to the
//corresponding button.
JButton button = new JButton(key);
button.addActionListener(numberListener);
button.setFont(BIGGER_FONT);
buttonPanel.add(button);
}
}

Now let us see how the corresponding code for any operation like add,subtraction,multiplication or division works..

String[] opOrder = {"+", "-", "*", "/","=","C"};
for (int i = 0; i < opOrder.length; i++) {
JButton button = new JButton(opOrder[i]);
button.addActionListener(operatorListener);
button.setFont(BIGGER_FONT);
panel.add(button);
}

Let us see how to design the actionListener method..

public void actionPerformed(ActionEvent e) {
if (number) {
action();
textfield.setText("0");
} else {
number = true;
String displayText = textfield.getText();
if (equalOp.equals("=")) {
operator.setTotal(displayText);
} else if (equalOp.equals("+")) {
operator.add(displayText);
} else if (equalOp.equals("-")) {
operator.subtract(displayText);
} else if (equalOp.equals("*")) {
operator.multiply(displayText);
} else if (equalOp.equals("/")) {
operator.divide(displayText);
}
textfield.setText("" + operator.getTotalString());
equalOp = e.getActionCommand();
}
}

Now let us check the functions in details…what the corresponding method will get called.

public CalculatorOperation() {
total = 0;
}
public String getTotalString() {
return ""+total;
}
public void setTotal(String n) {
total = convertToNumber(n);
}
public void add(String n) {
total += convertToNumber(n);
}
public void subtract(String n) {
total -= convertToNumber(n);
}
public void multiply(String n) {
total *= convertToNumber(n);
}

public void divide(String n) {
total /= convertToNumber(n);
}

private int convertToNumber(String n) {
return Integer.parseInt(n);
}
}

Real Implementation:

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

public class Calculator extends JFrame {
private final Font BIGGER_FONT = new Font("Ariel", Font.PLAIN, 20);
private JTextField textfield;
private boolean number = true;
private String equalOp = "=";
private CalculatorOperation operator = new CalculatorOperation();
public static void main(String[] args) {
JFrame frame = new Calculator();
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension screenSize = tk.getScreenSize();
final int WIDTH = screenSize.width;
final int HEIGHT = screenSize.height;
frame.setLocation(WIDTH / 4, WIDTH / 4);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public Calculator() {
textfield = new JTextField("0", 12);
textfield.setHorizontalAlignment(JTextField.RIGHT);
textfield.setFont(BIGGER_FONT);

ActionListener numberListener = new NumberListener();
String buttonOrder = "1234567890 ";
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(4, 4, 4, 4));
for (int i = 0; i < buttonOrder.length(); i++) {
String key = buttonOrder.substring(i, i+1);
if (key.equals(" ")) {
buttonPanel.add(new JLabel(""));
} else {
JButton button = new JButton(key);
button.addActionListener(numberListener);
button.setFont(BIGGER_FONT);
buttonPanel.add(button);
}
}
ActionListener operatorListener = new OperatorListener();
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(4, 4, 4, 4));
String[] opOrder = {"+", "-", "*", "/","=","C"};
for (int i = 0; i < opOrder.length; i++) {
JButton button = new JButton(opOrder[i]);
button.addActionListener(operatorListener);
button.setFont(BIGGER_FONT);
panel.add(button);
}

JPanel pan = new JPanel();
pan.setLayout(new BorderLayout(4, 4));
pan.add(textfield, BorderLayout.NORTH );
pan.add(buttonPanel , BorderLayout.CENTER);
pan.add(panel , BorderLayout.EAST );
this.setContentPane(pan);
this.pack();
this.setTitle("Calculator");
this.setResizable(false);
}
private void action() {
number = true;
textfield.setText("0");
equalOp = "=";
operator.setTotal("0");
}
class OperatorListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (number) {
action();
textfield.setText("0");
} else {
number = true;
String displayText = textfield.getText();
if (equalOp.equals("=")) {
operator.setTotal(displayText);
} else if (equalOp.equals("+")) {
operator.add(displayText);
} else if (equalOp.equals("-")) {
operator.subtract(displayText);
} else if (equalOp.equals("*")) {
operator.multiply(displayText);
} else if (equalOp.equals("/")) {
operator.divide(displayText);
}
textfield.setText("" + operator.getTotalString());
equalOp = e.getActionCommand();
}
}
}
class NumberListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
String digit = event.getActionCommand();
if (number) {
textfield.setText(digit);
number = false;
} else {
textfield.setText(textfield.getText() + digit);
}
}
}
public class CalculatorOperation {

private int total;
public CalculatorOperation() {
total = 0;
}
public String getTotalString() {
return ""+total;
}
public void setTotal(String n) {
total = convertToNumber(n);
}
public void add(String n) {
total += convertToNumber(n);
}
public void subtract(String n) {
total -= convertToNumber(n);
}
public void multiply(String n) {
total *= convertToNumber(n);
}

public void divide(String n) {
total /= convertToNumber(n);
}

private int convertToNumber(String n) {
return Integer.parseInt(n);
}
}

}
Output??

I tried to do 3-3=0.Here is the output.

Get The Jar–Your Own Calculator

Click Here to get the corresponding Calculator Jar

Basic Code structure is taken from RoseIndia

READ  How To Find Occurrence of A Word in a String in Java

READ  Abstract Class URLConnection in Java




Spread the love
Animesh Chatterjeehttps://techtravelhub.com/
I am the founder and owner of the blog - TechTravelHub.com, always love to share knowledge on test automation,tools,techniques and tips.I am a passionate coder of Java and VBScript.I also publish articles on Travel ideas and great honeymoon destinations.Apart from these, I am a gear-head,love to drive across India. I have shared lots of articles here on How to travel several parts of India.Customization of cars aka car modification is my another hobby.Get in touch with me on ani01104@gamil.com

Related Articles

Super Keyword in Java Simplified

Super Keyword Super Keyword in Java Simplified: Java defines a special keyword called...

Comments

  1. Hello there! This is kind of off topic but I need some help from an established blog.
    Is it very difficult to set up your own blog? I’m not very techincal but I can figure things out
    pretty fast. I’m thinking about setting up my own but I’m not sure where to start.
    Do you have any points or suggestions? Many thanks

  2. Attractive section of content. I just stumbled upon your site and in accession capital to
    assert that I get actually enjoyed account your blog posts.
    Any way I’ll be subscribing to your augment and even I achievement you
    access consistently quickly.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Recent Posts

Super Keyword in Java Simplified

Super Keyword Super Keyword in Java Simplified: Java defines a special...

Learn Object Repository in UFT in An Efficient and Fast Manner

Object Repository in UFT The post will cover the following...

Learn What Primary Tools For Test Automation

Primary Tools For Test Automation According to the Gartner report...

EDITOR PICKS


Spread the love