0% found this document useful (0 votes)
119 views20 pages

Calculator

This document describes a Java Swing-based GUI Calculator that performs basic arithmetic operations like addition, subtraction, multiplication, and division. It features an intuitive interface with buttons for digits and operations, employs event-driven programming for user interactions, and includes error handling to prevent invalid inputs. The project serves as a practical example for beginners to learn about GUI development and Java programming concepts.

Uploaded by

ragulm0122
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
119 views20 pages

Calculator

This document describes a Java Swing-based GUI Calculator that performs basic arithmetic operations like addition, subtraction, multiplication, and division. It features an intuitive interface with buttons for digits and operations, employs event-driven programming for user interactions, and includes error handling to prevent invalid inputs. The project serves as a practical example for beginners to learn about GUI development and Java programming concepts.

Uploaded by

ragulm0122
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

Abstract

CALCULATOR IN By

JAVA SWING Ragul M


Abstract
o This Java program presents a Graphical User Interface (GUI) Calculator built using Java
Swing, offering a user-friendly approach to performing basic arithmetic calculations. The
calculator supports fundamental operations such as addition, subtraction, multiplication,
and division, along with decimal number handling.

o Users can interact with the application through an intuitive interface consisting of digit
buttons (0-9), an equals button, arithmetic operation buttons, a decimal point button, and
a clear button to reset the input.

o The calculator dynamically updates the display as users enter numbers and operations,
providing real-time feedback on the input and computed results.

o The calculator employs Java's event-driven programming model, where each button click
triggers an event handled through an ActionListener. The logic behind calculations is
managed using an array to store numerical inputs and a flag system to track operator
selection.

o The program ensures smooth operation by checking user input before performing
calculations, thereby preventing common errors such as consecutive operator inputs or
division by zero.Graphically, the application is structured within a JFrame window, with
components such as JLabel for display and JButton elements for user input.

o The layout is designed for ease of use, featuring clearly distinguishable buttons with large
fonts and appropriate spacing to enhance accessibility. The calculator also implements
basic error handling mechanisms to improve usability and maintain stability during
operations.

o This project serves as an excellent example of Java Swing-based GUI development,


demonstrating key concepts such as event handling, layout management, and user input
validation.It is a practical implementation that showcases how Java can be utilized to
create interactive applications with real-world applications.

o Additionally, it lays the foundation for future enhancements, such as scientific functions,
memory operations, and a more advanced user interface.By developing this calculator,
programmers can gain hands-on experience in building GUI applications, managing user
interactions, and implementing logical processing in Java, making it an ideal project for
beginners and enthusiasts in software development.
OBJECTIVE
The primary objective of this Java program is to develop a Graphical User Interface (GUI)
Calculator using Java Swing that allows users to perform basic arithmetic operations in an
intuitive and interactive manner.
The calculator aims to provide a functional and user-friendly interface where users can input
numbers, perform calculations, and view results dynamically.

1. Implement a Basic Arithmetic Calculator


The calculator should support fundamental mathematical operations, including:
o Addition (+)
o Subtraction (-)
o Multiplication (×)
o Division (÷)
Users should be able to enter numbers and operators sequentially, with the program handling
calculations accordingly.

2. Develop a User-Friendly Graphical Interface

• The application is built using Java Swing, ensuring a visually structured and interactive
interface.
• The layout includes a numeric keypad (0-9), operator buttons, a decimal point button, an
equals button, and a clear button for resetting calculations.
• The display panel (JLabel) provides real-time updates based on user input, improving the
usability of the application.
• The buttons are designed with appropriate sizes and fonts to enhance accessibility.

3. Implement Event-Driven Programming Using ActionListeners

• Each button click triggers an event, handled using ActionListener to update the display
and execute calculations.
• The program follows an event-driven approach, responding dynamically to user
interactions without requiring manual input through a console.
4. Ensure Proper Input Handling and Error Prevention

• The calculator must prevent incorrect inputs, such as:


o Avoiding multiple consecutive operator presses.
o Handling decimal points properly to prevent invalid numbers.
o Restricting division by zero to prevent runtime errors.
• Logical conditions are implemented to validate user input before performing operations.

5. Implement Calculation Logic Efficiently

• The program uses an array (float[] a = new float[2]) to store numerical values and a flag
(x) to track selected operations.
• The = button should execute the stored operation on the two input numbers and display
the result correctly.
• After a calculation is performed, the program should reset appropriately to allow new
inputs.

6. Provide a Stable and Expandable Codebase

• The code is structured to allow future enhancements, such as:


o Additional mathematical functions (e.g., square root, exponentiation, memory
storage).
o Improved UI with themes and better button arrangements for ease of use.
o Error messages or validation prompts to enhance user experience.

7. Demonstrate Java Swing and GUI Programming Concepts

• The project serves as a learning tool for understanding:


o Swing components (JFrame, JButton, JLabel)
o Event handling with ActionListener
o Basic layout management and component positioning
o Handling user input dynamically in GUI-based applications
Introduction
o In the modern world of computing, Graphical User Interface (GUI)-based applications
play a crucial role in enhancing user experience and interaction.

o This project is a GUI-based Calculator developed using Java Swing, designed to perform
basic arithmetic operations such as addition, subtraction, multiplication, and division.

o The calculator provides an intuitive interface where users can input numbers using on-
screen buttons and execute calculations dynamically.

o The program follows an event-driven approach, where each button click triggers an
action that updates the display and processes the arithmetic operation accordingly. The
graphical interface is built using Swing components such as JFrame, JButton, and JLabel,
ensuring a smooth and visually appealing user experience.

o The calculator features a numeric keypad (0-9), an equals button, operator buttons, a
decimal point button, and a clear button, allowing users to perform calculations
seamlessly.

o One of the key aspects of this program is its efficient input handling. It ensures that users
cannot enter invalid inputs, such as multiple consecutive operators, improper decimal
usage, or division by zero, thereby preventing errors and ensuring stable performance.

o Additionally, the program follows a structured approach to handling numerical inputs,


storing values in an array, and executing operations based on user selection.

o This project serves as an excellent example of Java Swing-based GUI development,


demonstrating important concepts such as event handling, layout management, and user
interaction in Java applications.

o Furthermore, it lays the foundation for future enhancements, such as implementing


advanced mathematical functions, improving UI aesthetics, and incorporating additional
features like memory storage and scientific calculations.

o Through this project, learners can gain hands-on experience in developing interactive
GUI applications, managing user inputs, and implementing basic arithmetic logic in Java,
making it an ideal project for beginners and aspiring Java developers.
Methodology
The development of the GUI-based Calculator follows a systematic approach, incorporating Java
Swing for GUI components, event-driven programming for user interactions, and logical
processing for arithmetic operations.

1. Designing the Graphical User Interface (GUI)

The calculator's interface is created using Java Swing, ensuring an interactive and visually
structured layout. The design includes:

• A main application window (JFrame) that serves as the container for all UI components.
• A display label (JLabel) to show user inputs and results.
• Buttons (JButton) for digits (0-9), arithmetic operators (+, -, ×, ÷), a decimal point, an
equals button (=), and a clear button (C).
• Each button is properly positioned within the JFrame using the setBounds() method,
ensuring a structured layout.

2. Implementing Event-Driven Programming

Since Java Swing applications rely on user interactions, the program follows an event-driven
approach:

• Each button is assigned an ActionListener, which detects button clicks and triggers
appropriate actions.
• When a user clicks a digit button, the number is appended to the display.
• When an operator button is clicked, the first number is stored, and the display resets for
the next input.
• The equals (=) button performs the arithmetic operation based on the stored operator and
operands.
• The clear (C) button resets the display and stored values to allow fresh calculations.

3. Managing User Input and Arithmetic Operations

To handle calculations effectively, the program maintains:

• A float array (float[] a = new float[2]) to store numerical values.


• A variable x to track the selected arithmetic operation.
• A boolean flag (opr) to determine whether an operator has been pressed, ensuring correct
number storage and operation sequencing.
• The calculation process works as follows:
• The first number is stored in a[0] when an operator is clicked.
• The operator is identified using x (e.g., x=1 for addition, x=2 for subtraction, etc.).
• The second number is stored in a[1] when = is pressed.
• The appropriate mathematical operation is performed on a[0] and a[1].
• The result is displayed, and the program resets for further calculations.

4. Handling Errors and Edge Cases

• To ensure a smooth and error-free experience, the program includes:


• Input validation: Prevents consecutive operator presses and ensures correct decimal
placement.
• Division by zero handling: Avoids runtime errors by ensuring the denominator is not
zero.
• Proper resetting of stored values: Ensures calculations do not interfere with new
operations.

5. Displaying Results and Updating UI

• The final result is displayed dynamically using the JLabel component, allowing users to
see real-time updates. The program ensures that:
• After pressing =, the result remains on the screen until a new input is provided.
• The display resets upon pressing C, allowing fresh calculations.
Source Code
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;

public class Calculator implements ActionListener {

boolean opr = false;


String old;
int x = 0, i = 0;
float[] a = new float[2];
JFrame jf;
JLabel displayLabel;
JButton zeroB, oneB, twoB, threeB, fourB, fiveB, sixB, sevenB, eightB, nineB, dotB, divB,
mulB, minB, plusB, equalB,
clearB;

public Calculator() {
jf = new JFrame("Calculator");
jf.getContentPane().setBackground(Color.BLACK);

jf.setLayout(null);
jf.setSize(600, 600);
jf.setLocation(500, 150);

displayLabel = new JLabel();


displayLabel.setBackground(Color.gray);
displayLabel.setOpaque(true);
displayLabel.setBounds(30, 50, 540, 50);
displayLabel.setHorizontalAlignment(SwingConstants.RIGHT);
displayLabel.setForeground(Color.white);

jf.add(displayLabel);
sevenB = new JButton("7");
sevenB.setBounds(30, 130, 80, 80);
sevenB.setFont(new Font("Arial", Font.PLAIN, 40));
jf.add(sevenB);
sevenB.addActionListener(this);

eightB = new JButton("8");


eightB.setBounds(130, 130, 80, 80);
eightB.setFont(new Font("Arial", Font.PLAIN, 40));
jf.add(eightB);
eightB.addActionListener(this);

nineB = new JButton("9");


nineB.setBounds(230, 130, 80, 80);
nineB.setFont(new Font("Arial", Font.PLAIN, 40));
jf.add(nineB);
nineB.addActionListener(this);
fourB = new JButton("4");
fourB.setBounds(30, 230, 80, 80);
fourB.setFont(new Font("Arial", Font.PLAIN, 40));
jf.add(fourB);
fourB.addActionListener(this);

fiveB = new JButton("5");


fiveB.setBounds(130, 230, 80, 80);
fiveB.setFont(new Font("Arial", Font.PLAIN, 40));
jf.add(fiveB);
fiveB.addActionListener(this);

sixB = new JButton("6");


sixB.setBounds(230, 230, 80, 80);
sixB.setFont(new Font("Arial", Font.PLAIN, 40));
jf.add(sixB);
sixB.addActionListener(this);

oneB = new JButton("1");


oneB.setBounds(30, 330, 80, 80);
oneB.setFont(new Font("Arial", Font.PLAIN, 40));
jf.add(oneB);
oneB.addActionListener(this);

twoB = new JButton("2");


twoB.setBounds(130, 330, 80, 80);
twoB.setFont(new Font("Arial", Font.PLAIN, 40));
jf.add(twoB);
twoB.addActionListener(this);

threeB = new JButton("3");


threeB.setBounds(230, 330, 80, 80);
threeB.setFont(new Font("Arial", Font.PLAIN, 40));
jf.add(threeB);
threeB.addActionListener(this);

dotB = new JButton(".");


dotB.setBounds(30, 430, 80, 80);
dotB.setFont(new Font("Arial", Font.PLAIN, 40));
jf.add(dotB);
dotB.addActionListener(this);

zeroB = new JButton("0");


zeroB.setBounds(130, 430, 80, 80);
zeroB.setFont(new Font("Arial", Font.PLAIN, 40));
jf.add(zeroB);
zeroB.addActionListener(this);

equalB = new JButton("=");


equalB.setBounds(230, 430, 80, 80);
equalB.setFont(new Font("Arial", Font.PLAIN, 40));
jf.add(equalB);
equalB.setBackground(Color.blue);
equalB.addActionListener(this);
divB = new JButton("/");
divB.setBounds(330, 130, 80, 80);
divB.setFont(new Font("Arial", Font.PLAIN, 40));
jf.add(divB);
divB.addActionListener(this);

mulB = new JButton("x");


mulB.setBounds(330, 230, 80, 80);
mulB.setFont(new Font("Arial", Font.PLAIN, 40));
jf.add(mulB);
mulB.addActionListener(this);

minB = new JButton("-");


minB.setBounds(330, 330, 80, 80);
minB.setFont(new Font("Arial", Font.PLAIN, 40));
jf.add(minB);
minB.addActionListener(this);

plusB = new JButton("+");


plusB.setBounds(330, 430, 80, 80);
plusB.setFont(new Font("Arial", Font.PLAIN, 40));
jf.add(plusB);
plusB.addActionListener(this);

clearB = new JButton("C");


clearB.setBounds(430, 430, 80, 80);
clearB.setFont(new Font("Arial", Font.PLAIN, 40));
jf.add(clearB);
clearB.addActionListener(this);

jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

public static void main(String[] args) {


new Calculator();
}

@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == sevenB) {
if (opr) {
displayLabel.setText("7");
opr = false;

} else {
displayLabel.setText(displayLabel.getText() + "7");

} else if (e.getSource() == eightB) {


if (opr) {
displayLabel.setText("8");
opr = false;
} else {
displayLabel.setText(displayLabel.getText() + "8");
}

} else if (e.getSource() == nineB) {


if (opr) {
displayLabel.setText("9");
opr = false;
} else {
displayLabel.setText(displayLabel.getText() + "9");

} else if (e.getSource() == oneB) {


if (opr) {
displayLabel.setText("1");
opr = false;
} else {
displayLabel.setText(displayLabel.getText() + "1");

} else if (e.getSource() == twoB) {


if (opr) {
displayLabel.setText("2");
opr = false;
} else {
displayLabel.setText(displayLabel.getText() + "2");
}
} else if (e.getSource() == threeB) {
if (opr) {
displayLabel.setText("3");
opr = false;

} else {
displayLabel.setText(displayLabel.getText() + "3");

} else if (e.getSource() == fourB) {


if (opr) {
displayLabel.setText("4");
opr = false;

} else {
displayLabel.setText(displayLabel.getText() + "4");

} else if (e.getSource() == fiveB) {


if (opr) {
displayLabel.setText("5");
opr = false;
} else {
displayLabel.setText(displayLabel.getText() + "5");
}
} else if (e.getSource() == sixB) {
if (opr) {
displayLabel.setText("6");
opr = false;

} else {
displayLabel.setText(displayLabel.getText() + "6");

} else if (e.getSource() == zeroB) {


if (opr) {
displayLabel.setText("0");
opr = false;

} else {
displayLabel.setText(displayLabel.getText() + "0");

} else if (e.getSource() == dotB) {


if (opr) {

opr = false;
displayLabel.setText(".");

} else {
displayLabel.setText(displayLabel.getText() + ".");

}
} else if (e.getSource() == plusB) {
opr = true;
old = displayLabel.getText();
x = 1;
a[i] = Float.parseFloat(old);
i = i + 1;

} else if (e.getSource() == minB) {


opr = true;
old = displayLabel.getText();
x = 2;
a[i++] = Float.parseFloat(old);

} else if (e.getSource() == divB) {


opr = true;
old = displayLabel.getText();
x = 4;
a[i++] = Float.parseFloat(old);

} else if (e.getSource() == mulB) {


opr = true;
old = displayLabel.getText();
x = 3;
a[i++] = Float.parseFloat(old);
} else if (e.getSource() == equalB) {
a[1] = Float.parseFloat(displayLabel.getText());
if (x == 1) {
a[0] += a[1];
i = 0;

} else if (x == 2) {
a[0] -= a[1];
} else if (x == 3) {
a[0] *= a[1];
} else if (x == 4) {
a[0] /= a[1];
}
i = 1;
x = 0;

displayLabel.setText(a[0] + "");

} else if (e.getSource() == clearB) {


displayLabel.setText("");
a[1] = a[0] = 0;
i = 0;
}

}
}
Output:
Conclusion
o The GUI-based Calculator using Java Swing efficiently performs basic arithmetic
operations with a user-friendly interface. It demonstrates event-driven programming, GUI
design, and input validation, serving as a foundation for advanced Java applications.
Future improvements could include scientific functions and enhanced UI design.

You might also like