0% found this document useful (0 votes)
126 views12 pages

Mycalculator

The document provides the source code for building a basic calculator application in Java using the AWT/Swing GUI toolkit. The code defines classes for digit, operator, memory and special buttons that update the display label when clicked. The main class initializes the frame and button components and handles event handling.

Uploaded by

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

Mycalculator

The document provides the source code for building a basic calculator application in Java using the AWT/Swing GUI toolkit. The code defines classes for digit, operator, memory and special buttons that update the display label when clicked. The main class initializes the frame and button components and handles event handling.

Uploaded by

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

?

Javatpoint Logo
Custom Search

Home
Java
C
C++
C#
Servlet
JSP
EJB
Struts2
Mail
Hibernate
Spring
Android
Design P
Quiz
Projects
Interview Q
Comment
Forum
Training

Basics of Java
OOPs Concepts
Java String
Java Regex
Exception Handling
Java Inner classes
Java Multithreading
Java I/O
Java Networking
Java AWT & Events
Java Swing
Swing IntroductionJava JButtonJava JLabelJava JTextFieldJava JTextAreaJava
JPasswordFieldJava JCheckBoxJava JRadioButtonJava JComboBoxJava JTableJava
JListJava JOptionPaneJava JScrollBarJava JMenuItem & JMenuJava JPopupMenuJava
JCheckBoxMenuItemJava JSeparatorJava JProgressBarJava JTreeJava JColorChooserJava
JTabbedPaneJava JSliderJava JSpinnerJava JDialogJava JPanelJava JFileChooserJava
JToggleButtonJava JToolBarJava JViewportJava JFrameJava JComponentJava
JLayeredPaneJava JDesktopPaneJava JEditorPaneJava JScrollPaneJava JSplitPaneJava
JTextPaneJava JRootPaneUsing ToolTipChange Title IconExecutable Jar FileDigital
WatchGraphics in swingDisplaying Image
Java Swing Apps
NotepadCalculatorIP FinderWord CounterURL Source GeneratorFolder ExplorerPuzzle
GamePic Puzzle GameTic Tac Toe GameOnline Exam
LayoutManagers
BorderLayoutGridLayoutFlowLayoutBoxLayoutCardLayoutGridBagLayoutGroupLayoutSpringLa
youtScrollPaneLayout
JavaFX
Java Applet
Java Reflection
Java Date
Java Conversion
Java Collection
Java JDBC
Java New Features
RMI
Internationalization
Interview Questions
JavaTpoint
next ??prev
Calculator in Java with Source Code
Calculator in Java with Source Code: We can develop calculator in java with the
help of AWT/Swing with event handling. Let's see the code of creating calculator in
java.

/*********************************************
Save this file as MyCalculator.java
to compile it use
javac MyCalculator.java
to use the calcuator do this
java MyCalculator

**********************************************/
import java.awt.*;
import java.awt.event.*;
/*********************************************/

public class MyCalculator extends Frame


{

public boolean setClear=true;


double number, memValue;
char op;

String digitButtonText[] = {"7", "8", "9", "4", "5", "6", "1", "2", "3", "0",
"+/-", "." };
String operatorButtonText[] = {"/", "sqrt", "*", "%", "-", "1/X", "+", "=" };
String memoryButtonText[] = {"MC", "MR", "MS", "M+" };
String specialButtonText[] = {"Backspc", "C", "CE" };

MyDigitButton digitButton[]=new MyDigitButton[digitButtonText.length];


MyOperatorButton operatorButton[]=new MyOperatorButton[operatorButtonText.length];

MyMemoryButton memoryButton[]=new MyMemoryButton[memoryButtonText.length];


MySpecialButton specialButton[]=new MySpecialButton[specialButtonText.length];

Label displayLabel=new Label("0",Label.RIGHT);


Label memLabel=new Label(" ",Label.RIGHT);

final int FRAME_WIDTH=325,FRAME_HEIGHT=325;


final int HEIGHT=30, WIDTH=30, H_SPACE=10,V_SPACE=10;
final int TOPX=30, TOPY=50;
///////////////////////////
MyCalculator(String frameText)//constructor
{
super(frameText);

int tempX=TOPX, y=TOPY;


displayLabel.setBounds(tempX,y,240,HEIGHT);
displayLabel.setBackground(Color.BLUE);
displayLabel.setForeground(Color.WHITE);
add(displayLabel);

memLabel.setBounds(TOPX, TOPY+HEIGHT+ V_SPACE,WIDTH, HEIGHT);


add(memLabel);

// set Co-ordinates for Memory Buttons


tempX=TOPX;
y=TOPY+2*(HEIGHT+V_SPACE);
for(int i=0; i<memoryButton.length; i++)
{
memoryButton[i]=new MyMemoryButton(tempX,y,WIDTH,HEIGHT,memoryButtonText[i], this);

memoryButton[i].setForeground(Color.RED);
y+=HEIGHT+V_SPACE;
}

//set Co-ordinates for Special Buttons


tempX=TOPX+1*(WIDTH+H_SPACE); y=TOPY+1*(HEIGHT+V_SPACE);
for(int i=0;i<specialButton.length;i++)
{
specialButton[i]=new MySpecialButton(tempX,y,WIDTH*2,HEIGHT,specialButtonText[i],
this);
specialButton[i].setForeground(Color.RED);
tempX=tempX+2*WIDTH+H_SPACE;
}

//set Co-ordinates for Digit Buttons


int digitX=TOPX+WIDTH+H_SPACE;
int digitY=TOPY+2*(HEIGHT+V_SPACE);
tempX=digitX; y=digitY;
for(int i=0;i<digitButton.length;i++)
{
digitButton[i]=new MyDigitButton(tempX,y,WIDTH,HEIGHT,digitButtonText[i], this);
digitButton[i].setForeground(Color.BLUE);
tempX+=WIDTH+H_SPACE;
if((i+1)%3==0){tempX=digitX; y+=HEIGHT+V_SPACE;}
}

//set Co-ordinates for Operator Buttons


int opsX=digitX+2*(WIDTH+H_SPACE)+H_SPACE;
int opsY=digitY;
tempX=opsX; y=opsY;
for(int i=0;i<operatorButton.length;i++)
{
tempX+=WIDTH+H_SPACE;
operatorButton[i]=new MyOperatorButton(tempX,y,WIDTH,HEIGHT,operatorButtonText[i],
this);
operatorButton[i].setForeground(Color.RED);
if((i+1)%2==0){tempX=opsX; y+=HEIGHT+V_SPACE;}
}

addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent ev)
{System.exit(0);}
});

setLayout(null);
setSize(FRAME_WIDTH,FRAME_HEIGHT);
setVisible(true);
}
//////////////////////////////////
static String getFormattedText(double temp)
{
String resText=""+temp;
if(resText.lastIndexOf(".0")>0)
resText=resText.substring(0,resText.length()-2);
return resText;
}
////////////////////////////////////////
public static void main(String []args)
{
new MyCalculator("Calculator - JavaTpoint");
}
}

/*******************************************/

class MyDigitButton extends Button implements ActionListener


{
MyCalculator cl;

//////////////////////////////////////////
MyDigitButton(int x,int y, int width,int height,String cap, MyCalculator clc)
{
super(cap);
setBounds(x,y,width,height);
this.cl=clc;
this.cl.add(this);
addActionListener(this);
}
////////////////////////////////////////////////
static boolean isInString(String s, char ch)
{
for(int i=0; i<s.length();i++) if(s.charAt(i)==ch) return true;
return false;
}
/////////////////////////////////////////////////
public void actionPerformed(ActionEvent ev)
{
String tempText=((MyDigitButton)ev.getSource()).getLabel();

if(tempText.equals("."))
{
if(cl.setClear)
{cl.displayLabel.setText("0.");cl.setClear=false;}
else if(!isInString(cl.displayLabel.getText(),'.'))
cl.displayLabel.setText(cl.displayLabel.getText()+".");
return;
}

int index=0;
try{
index=Integer.parseInt(tempText);
}catch(NumberFormatException e){return;}

if (index==0 && cl.displayLabel.getText().equals("0")) return;

if(cl.setClear)
{cl.displayLabel.setText(""+index);cl.setClear=false;}
else
cl.displayLabel.setText(cl.displayLabel.getText()+index);
}//actionPerformed
}//class defination

/********************************************/

class MyOperatorButton extends Button implements ActionListener


{
MyCalculator cl;

MyOperatorButton(int x,int y, int width,int height,String cap, MyCalculator clc)


{
super(cap);
setBounds(x,y,width,height);
this.cl=clc;
this.cl.add(this);
addActionListener(this);
}
///////////////////////
public void actionPerformed(ActionEvent ev)
{
String opText=((MyOperatorButton)ev.getSource()).getLabel();

cl.setClear=true;
double temp=Double.parseDouble(cl.displayLabel.getText());

if(opText.equals("1/x"))
{
try
{double tempd=1/(double)temp;
cl.displayLabel.setText(MyCalculator.getFormattedText(tempd));}
catch(ArithmeticException excp)
{cl.displayLabel.setText("Divide by 0.");}
return;
}
if(opText.equals("sqrt"))
{
try
{double tempd=Math.sqrt(temp);
cl.displayLabel.setText(MyCalculator.getFormattedText(tempd));}
catch(ArithmeticException excp)
{cl.displayLabel.setText("Divide by 0.");}
return;
}
if(!opText.equals("="))
{
cl.number=temp;
cl.op=opText.charAt(0);
return;
}
// process = button pressed
switch(cl.op)
{
case '+':
temp+=cl.number;break;
case '-':
temp=cl.number-temp;break;
case '*':
temp*=cl.number;break;
case '%':
try{temp=cl.number%temp;}
catch(ArithmeticException excp)
{cl.displayLabel.setText("Divide by 0."); return;}
break;
case '/':
try{temp=cl.number/temp;}
catch(ArithmeticException excp)
{cl.displayLabel.setText("Divide by 0."); return;}
break;
}//switch

cl.displayLabel.setText(MyCalculator.getFormattedText(temp));
//cl.number=temp;
}//actionPerformed
}//class

/****************************************/

class MyMemoryButton extends Button implements ActionListener


{
MyCalculator cl;

/////////////////////////////////
MyMemoryButton(int x,int y, int width,int height,String cap, MyCalculator clc)
{
super(cap);
setBounds(x,y,width,height);
this.cl=clc;
this.cl.add(this);
addActionListener(this);
}
////////////////////////////////////////////////
public void actionPerformed(ActionEvent ev)
{
char memop=((MyMemoryButton)ev.getSource()).getLabel().charAt(1);

cl.setClear=true;
double temp=Double.parseDouble(cl.displayLabel.getText());

switch(memop)
{
case 'C':
cl.memLabel.setText(" ");cl.memValue=0.0;break;
case 'R':
cl.displayLabel.setText(MyCalculator.getFormattedText(cl.memValue));break;
case 'S':
cl.memValue=0.0;
case '+':
cl.memValue+=Double.parseDouble(cl.displayLabel.getText());
if(cl.displayLabel.getText().equals("0") ||
cl.displayLabel.getText().equals("0.0") )
cl.memLabel.setText(" ");
else
cl.memLabel.setText("M");
break;
}//switch
}//actionPerformed
}//class
/*****************************************/

class MySpecialButton extends Button implements ActionListener


{
MyCalculator cl;

MySpecialButton(int x,int y, int width,int height,String cap, MyCalculator clc)


{
super(cap);
setBounds(x,y,width,height);
this.cl=clc;
this.cl.add(this);
addActionListener(this);
}
//////////////////////
static String backSpace(String s)
{
String Res="";
for(int i=0; i<s.length()-1; i++) Res+=s.charAt(i);
return Res;
}

//////////////////////////////////////////////////////////
public void actionPerformed(ActionEvent ev)
{
String opText=((MySpecialButton)ev.getSource()).getLabel();
//check for backspace button
if(opText.equals("Backspc"))
{
String tempText=backSpace(cl.displayLabel.getText());
if(tempText.equals(""))
cl.displayLabel.setText("0");
else
cl.displayLabel.setText(tempText);
return;
}
//check for "C" button i.e. Reset
if(opText.equals("C"))
{
cl.number=0.0; cl.op=' '; cl.memValue=0.0;
cl.memLabel.setText(" ");
}

//it must be CE button pressed


cl.displayLabel.setText("0");cl.setClear=true;
}//actionPerformed
}//class

/*********************************************
Features not implemented and few bugs

i) No coding done for "+/-" button.


ii) Menubar is not included.
iii)Not for Scientific calculation
iv)Some of the computation may lead to unexpected result
due to the representation of Floating point numbers in computer
is an approximation to the given value that can be stored
physically in memory.
***********************************************/
download this example
Calculator in Java with source code
Next TopicIP Finder in Java

? prevnext ?

Help Others, Please Share


facebook twitter pinterest

Learn Latest Tutorials


Openpyxl Tutorial
Openpyxl

Tally Tutorial
Tally

Godot Tutorial
Godot

Spring Boot Tutorial


Spring Boot

Gradle Tutorial
Gradle

UML Tutorial
UML

Artificial Neural Network Tutorial


ANN

ES6 Tutorial
ES6

Flutter Tutorial
Flutter

Selenium Python
Selenium Py

Firebase Tutorial
Firebase

Cobol Tutorial
Cobol

Preparation
Aptitude
Aptitude

Logical Reasoning
Reasoning

Verbal Ability
Verbal A.
Interview Questions
Interview

Company Interview Questions


Company

Trending Technologies
Artificial Intelligence Tutorial
AI

AWS Tutorial
AWS

Selenium tutorial
Selenium

Cloud tutorial
Cloud

Hadoop tutorial
Hadoop

ReactJS Tutorial
ReactJS

Data Science Tutorial


D. Science

Angular 7 Tutorial
Angular 7

Blockchain Tutorial
Blockchain

Git Tutorial
Git

Machine Learning Tutorial


ML

DevOps Tutorial
DevOps

B.Tech / MCA
DBMS tutorial
DBMS

Data Structures tutorial


DS

DAA tutorial
DAA

Operating System tutorial


OS

Computer Network tutorial


C. Network
Compiler Design tutorial
Compiler D.

Computer Organization and Architecture


COA

Discrete Mathematics Tutorial


D. Math.

Ethical Hacking Tutorial


E. Hacking

Computer Graphics Tutorial


C. Graphics

Software Engineering Tutorial


Software E.

html tutorial
Web Tech.

Cyber Security tutorial


Cyber Sec.

Automata Tutorial
Automata

C Language tutorial
C

C++ tutorial
C++

Java tutorial
Java

.Net Framework tutorial


.Net

Python tutorial
Python

List of Programs
Programs

Control Systems tutorial


Control S.

Data Mining Tutorial


Data Mining

Javatpoint Services
JavaTpoint offers too many high quality services. Mail us on [email protected], to
get more information about given services.
Website Designing
Website Development
Java Development
PHP Development
WordPress
Graphic Designing
Logo
Digital Marketing
On Page and Off Page SEO
PPC
Content Development
Corporate Training
Classroom and Online Training
Data Entry
Training For College Campus
JavaTpoint offers college campus training on Core Java, Advance Java, .Net,
Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at
[email protected].
Duration: 1 week to 2 week

Like/Subscribe us for latest updates or newsletter RSS Feed Subscribe to Get Email
Alerts Facebook Page Twitter Page YouTube Blog Page
LEARN TUTORIALS
Learn Java
Learn Data Structures
Learn C Programming
Learn C++ Tutorial
Learn C# Tutorial
Learn PHP Tutorial
Learn HTML Tutorial
Learn JavaScript Tutorial
Learn jQuery Tutorial
Learn Spring Tutorial
OUR WEBSITES
Javatpoint.com
Hindi100.com
Lyricsia.com
Quoteperson.com
Jobandplacement.com
OUR SERVICES
Website Development

Android Development

Website Designing

Digital Marketing

Summer Training

Industrial Training

College Campus Training

CONTACT
Address: G-13, 2nd Floor, Sec-3

Noida, UP, 201301, India


Contact No: 0120-4256464, 9990449935

Contact Us
Subscribe Us
Privacy Policy
Sitemap

About Me
� Copyright 2011-2018 www.javatpoint.com. All rights reserved. Developed by
JavaTpoint.

You might also like