Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Login         

View Questions and Answers by Category

Advertisements


 
Have Programming Question? Ask it here!
 
 
 


aman
Computers
7 Answer(s)      6 years and 9 months ago
Posted in : Java Beginners



Advertisement
View Answers

May 1, 2008 at 6:53 PM


Hi,

import java.awt.*;
import java.awt.event.*;
import java.awt.event.ActionListener;

class CalcFrame extends Frame {
CalcFrame( String str) {
// call to superclass
super(str);
// to close the calculator(Frame)
addWindowListener(new WindowAdapter() {
public void windowClosing (WindowEvent we) {
System.exit(0);
}
});
}
}

public class Calculator implements ActionListener, ItemListener {
// creating instances of objects
CalcFrame fr;
MenuBar menu;
Menu view, font;
MenuItem bold, regular;
CheckboxMenuItem basic ;
CheckboxGroup cbg;
Checkbox radians, degrees;
TextField display;
Button key[] = new Button[20]; // creates a button object array of 20
Button clearAll, clearEntry, round;
Button scientificKey[] = new Button[10]; // creates a button array of 8
// declaring variables
boolean addButtonPressed, subtractButtonPressed, multiplyButtonPressed;
boolean divideButtonPressed, decimalPointPressed, powerButtonPressed;
boolean roundButtonPressed = false;
double initialNumber; // the first number for the two number operation
double currentNumber = 0; // the number shown in the screen while it is being pressed
int decimalPlaces = 0;

// main function
public static void main (String args[]) {
// constructor
Calculator cal = new Calculator();
cal.makeCalculator();
}

public void makeCalculator() {
// size of the button
final int BWIDTH = 25;
final int BHEIGHT = 25;
int count =1;
// create frame for the calculator
fr = new CalcFrame("Simple Calculator");
// set the size
fr.setSize(300,270);
fr.setBackground(Color.pink);;
// create a menubar for the frame
menu = new MenuBar();
// add menu the menubar
view = new Menu("View");
font = new Menu ("Font");
// create instance of object for View menu
basic = new CheckboxMenuItem("Basic",true);
// add a listener to receive item events when the state of an item changes
basic.addItemListener(this);
// create instance of object for font menu
bold = new MenuItem("Arial Bold");
bold.addActionListener(this);

regular = new MenuItem("Arial Regular");
regular.addActionListener(this);
view.add(basic);
font.add(bold);
font.add(regular);

// add the menus in the menubar
menu.add(view);
menu.add(font);
// add menubar to the frame
fr.setMenuBar(menu);
// override the layout manager
fr.setLayout(null);
// set the initial numbers that is 1 to 9
for (int row = 0; row < 3; ++row) {
for (int col = 0; col < 3; ++col) {
// this will set the key from 1 to 9
key[count] = new Button(Integer.toString(count));
key[count].addActionListener(this);
// set the boundry for the keys
key[count].setBounds(30*(col + 1), 30*(row + 4),BWIDTH,BHEIGHT);
key[count].setBackground(Color.yellow);
// add to the frame
fr.add(key[count++]);
}
}


May 1, 2008 at 6:56 PM


// Now create, addlistener and add to frame all other keys
key[0] = new Button("0");
key[0].addActionListener(this);
key[0].setBounds(30,210,BWIDTH,BHEIGHT);
key[0].setBackground(Color.yellow);
fr.add(key[0]);

//decimal
key[10] = new Button(".");
key[10].addActionListener(this);
key[10].setBounds(60,210,BWIDTH,BHEIGHT);
key[10].setBackground(Color.yellow);
fr.add(key[10]);

//equals to
key[11] = new Button("=");
key[11].addActionListener(this);
key[11].setBounds(90,210,BWIDTH,BHEIGHT);
key[11].setBackground(Color.yellow);
fr.add(key[11]);

//multiply
key[12] = new Button("*");
key[12].addActionListener(this);
key[12].setBounds(120,120,BWIDTH,BHEIGHT);
key[12].setBackground(Color.yellow);
fr.add(key[12]);

//divide
key[13] = new Button("/");
key[13].addActionListener(this);
key[13].setBounds(120,150,BWIDTH,BHEIGHT);
key[13].setBackground(Color.yellow);
fr.add(key[13]);

//addition
key[14] = new Button("+");
key[14].addActionListener(this);
key[14].setBounds(120,180,BWIDTH,BHEIGHT);
key[14].setBackground(Color.yellow);
fr.add(key[14]);

//subtract
key[15] = new Button("-");
key[15].addActionListener(this);
key[15].setBounds(120,210,BWIDTH,BHEIGHT);
key[15].setBackground(Color.yellow);
fr.add(key[15]);

//reciprocal
key[16] = new Button("1/x");
key[16].addActionListener(this);
key[16].setBounds(150,120,BWIDTH,BHEIGHT);
key[16].setBackground(Color.yellow);
fr.add(key[16]);

//power
key[17] = new Button("x^n");
key[17].addActionListener(this);
key[17].setBounds(150,150,BWIDTH,BHEIGHT);
key[17].setBackground(Color.yellow);
fr.add(key[17]);

//change sign
key[18] = new Button("+/-");
key[18].addActionListener(this);
key[18].setBounds(150,180,BWIDTH,BHEIGHT);
key[18].setBackground(Color.yellow);
fr.add(key[18]);

//factorial
key[19] = new Button("x!");
key[19].addActionListener(this);
key[19].setBounds(150,210,BWIDTH,BHEIGHT);
key[19].setBackground(Color.yellow);
fr.add(key[19]);

// CA
clearAll = new Button("CA");
clearAll.addActionListener(this);
clearAll.setBounds(30, 240, BWIDTH+20, BHEIGHT);
clearAll.setBackground(Color.yellow);
fr.add(clearAll);

// CE
clearEntry = new Button("CE");
clearEntry.addActionListener(this);
clearEntry.setBounds(80, 240, BWIDTH+20, BHEIGHT);
clearEntry.setBackground(Color.yellow);
fr.add(clearEntry);

// round
round = new Button("Round");
round.addActionListener(this);
round.setBounds(130, 240, BWIDTH+20, BHEIGHT);
round.setBackground(Color.yellow);
fr.add(round);

// set display area
display = new TextField("0");
display.setBounds(30,90,150,20);
display.setBackground(Color.white);


May 1, 2008 at 6:56 PM


cbg = new CheckboxGroup();
degrees = new Checkbox("Degrees", cbg, true);
radians = new Checkbox("Radians", cbg, false);
degrees.addItemListener(this);
radians.addItemListener(this);

degrees.setBounds(185, 75, 3 * BWIDTH, BHEIGHT);
radians.setBounds(185, 95, 3 * BWIDTH, BHEIGHT);
degrees.setVisible(false);
radians.setVisible(false);
fr.add(degrees);
fr.add(radians);
fr.add(display);
fr.setVisible(true);
} // end of makeCalculator

public void actionPerformed(ActionEvent ae) {
String buttonText = ae.getActionCommand();
double displayNumber = Double.valueOf(display.getText()).doubleValue();

// if the button pressed text is 0 to 9
if((buttonText.charAt(0) >= '0') & (buttonText.charAt(0) <= '9')) {
if(decimalPointPressed) {
for (int i=1;i <=decimalPlaces; ++i)
currentNumber *= 10;
currentNumber +=(int)buttonText.charAt(0)- (int)'0';
for (int i=1;i <=decimalPlaces; ++i) {
currentNumber /=10;
}
++decimalPlaces;
display.setText(Double.toString(currentNumber));
}
else if (roundButtonPressed) {
int decPlaces = (int)buttonText.charAt(0) - (int)'0';
for (int i=0; i< decPlaces; ++i)
displayNumber *=10;
displayNumber = Math.round(displayNumber);

for (int i = 0; i < decPlaces; ++i) {
displayNumber /=10;

}

display.setText(Double.toString(displayNumber));
roundButtonPressed = false;
}
else {
currentNumber = currentNumber * 10 + (int)buttonText.charAt(0)-(int)'0';
display.setText(Integer.toString((int)currentNumber));
}
}


May 1, 2008 at 6:57 PM


if(buttonText == "+") {
addButtonPressed = true;
initialNumber = displayNumber;
currentNumber = 0;
decimalPointPressed = false;
}

// if button pressed is subtract

if (buttonText == "-") {
subtractButtonPressed = true;
initialNumber = displayNumber;
currentNumber = 0;
decimalPointPressed = false;
}

// if button pressed is divide
if (buttonText == "/") {
divideButtonPressed = true;
initialNumber = displayNumber;
currentNumber = 0;
decimalPointPressed = false;
}

// if button pressed is multiply
if (buttonText == "*") {
multiplyButtonPressed = true;
initialNumber = displayNumber;
currentNumber = 0;
decimalPointPressed = false;
}

// if button pressed is reciprocal
if (buttonText == "1/x") {
// call reciprocal method
display.setText(reciprocal(displayNumber));
currentNumber = 0;
decimalPointPressed = false;
}

// if button is pressed to change a sign
if (buttonText == "+/-") {
// call changesign meyhod to change the sign
display.setText(changeSign(displayNumber));
currentNumber = 0;
decimalPointPressed = false;
}

// factorial button
if (buttonText == "x!") {
display.setText(factorial(displayNumber));
currentNumber = 0;
decimalPointPressed = false;
}
// power button
if (buttonText == "x^n") {
powerButtonPressed = true;
initialNumber = displayNumber;
currentNumber = 0;
decimalPointPressed = false;
}


May 1, 2008 at 6:58 PM


// this will convert the numbers displayed to degrees
if (buttonText == "todeg")
display.setText(Double.toString(Math.toDegrees(displayNumber)));
// this will convert the numbers displayed to radians
if (buttonText == "torad")
display.setText(Double.toString(Math.toRadians(displayNumber)));

if (buttonText == "Pi") {
display.setText(Double.toString(Math.PI));
currentNumber =0;
decimalPointPressed = false;
}

if (buttonText == "Round")
roundButtonPressed = true;

// check if decimal point is pressed
if (buttonText == ".") {
String displayedNumber = display.getText();
boolean decimalPointFound = false;
int i;

decimalPointPressed = true;
// check for decimal point
for (i =0; i < displayedNumber.length(); ++i) {
if(displayedNumber.charAt(i) == '.') {
decimalPointFound = true;
continue;
}
}
if (!decimalPointFound)
decimalPlaces = 1;
}

if(buttonText == "CA"){
// set all buttons to false
resetAllButtons();
display.setText("0");
currentNumber = 0;
}

if (buttonText == "CE") {
display.setText("0");
currentNumber = 0;
decimalPointPressed = false;
}
if (buttonText == "E") {
display.setText(Double.toString(Math.E));
currentNumber = 0;
decimalPointPressed = false;
}


May 1, 2008 at 6:59 PM


// the main action

if (buttonText == "=") {
currentNumber = 0;
// if add button is pressed
if(addButtonPressed)
display.setText(Double.toString(initialNumber + displayNumber));
// if subtract button is pressed
if(subtractButtonPressed)
display.setText(Double.toString(initialNumber - displayNumber));
// if divide button is pressed
if (divideButtonPressed) {
// check if the divisor is zero
if(displayNumber == 0) {
MessageBox mb = new MessageBox ( fr, "Error ", true, "Cannot divide by zero.");
mb.show();
}
else
display.setText(Double.toString(initialNumber/displayNumber));
}

// if multiply button is pressed
if(multiplyButtonPressed)
display.setText(Double.toString(initialNumber * displayNumber));
// if power button is pressed
if (powerButtonPressed)
display.setText(power(initialNumber, displayNumber));

// set all the buttons to false
resetAllButtons();
}

if (buttonText == "Arial Regular") {
for (int i =0; i < 10; ++i)
key[i].setFont(new Font("Arial", Font.PLAIN, 12));
}

if (buttonText == "Arial Bold") {
for (int i =0; i < 10; ++i)
key[i].setFont(new Font("Arial", Font.BOLD, 12));
}

} // end of action events

public void itemStateChanged(ItemEvent ie){
if (ie.getItem() == "Basic") {
basic.setState(true);
// scientific.setState(false);
fr.setTitle("Basic Calculator Example");
fr.setSize(200,270);
// check if the scientific keys are visible. if true hide them
if (scientificKey[0].isVisible()) {
for (int i=0; i < 8; ++i)
scientificKey[i].setVisible(false);
radians.setVisible(false);
degrees.setVisible(false);
}
}

} // end of itemState


May 1, 2008 at 7:00 PM


public void resetAllButtons() {
addButtonPressed = false;
subtractButtonPressed = false;
multiplyButtonPressed = false;
divideButtonPressed = false;
decimalPointPressed = false;
powerButtonPressed = false;
roundButtonPressed = false;
}

public String factorial(double num) {
int theNum = (int)num;
if (theNum < 1) {
MessageBox mb = new MessageBox (fr, "Facorial Error", true,
"Cannot find the factorial of numbers less than 1.");
mb.show();
return("0");
}
else {
for (int i=(theNum -1); i > 1; --i)
theNum *= i;
return Integer.toString(theNum);
}
}

public String reciprocal(double num) {
if (num ==0) {
MessageBox mb = new MessageBox(fr,"Reciprocal Error", true,
"Cannot find the reciprocal of 0");
mb.show();
}
else
num = 1/num;
return Double.toString(num);
}

public String power (double base, double index) {
return Double.toString(Math.pow(base, index));
}

public String changeSign(double num) {
return Double.toString(-num);
}
}

class MessageBox extends Dialog implements ActionListener {
Button ok;
MessageBox(Frame f, String title, boolean mode, String message) {
super(f, title, mode);
Panel centrePanel = new Panel();
Label lbl = new Label(message);
centrePanel.add(lbl);
add(centrePanel, "Center");
Panel southPanel = new Panel();
ok = new Button ("OK");
ok.addActionListener(this);
southPanel.add(ok);
add(southPanel, "South");
pack();
addWindowListener (new WindowAdapter(){
public void windowClosing (WindowEvent we) {
System.exit(0);
}
});
}
public void actionPerformed(ActionEvent ae) {
dispose();
}
}

-------------------------

read for more information,

http://www.roseindia.net/java/


Related Tutorials/Questions & Answers:
computers - Java Beginners
computers   Describe any 5 methods in any of the library classes of java?  Hi Friend, Please visit the following link: http://www.roseindia.net/java/java-get-example/index.shtml Here you will get lot
Advertisements
How to develope web service with exachanging xml message between computers using SOAP
How to develope web service with exachanging xml message between computers using SOAP  Hi Friends, I want to developed a webservice using soap as a protocol,in this webservice the client sends a set of 15 parameters and program
E Book Witing
Ebook writing eBook Writing As computers are gaining control of the world, the trend of paper books is out and that of eBooks are sweeping
Java UDP
Java UDP       TCP and UDP are transport protocols used for communication between computers. UDP(User Datagram Protocol) is a very simple connectionless protocol. UDP can
EBook Witing
eBook Writing As computers are gaining control of the world, the trend of paper books is out and that of eBooks are sweeping in. Writing and publishing eBooks has become hugely popular amongst writers
Domain Name
The domain name system (DNS) is a series of letters and numbers that are separated by periods and used to name organizations, computers and addresses on the Internet. The domain name is the way that Internet names are located
The Open Source World is a Big Part of PHP
The PHP scripting language is something that can work on many types of computers and can be used alongside HTML. It is also able to work with a variety of different forms of technology. The big reason for this comes from how PHP is an open
Amazon Web Services (AWS)
, magazines, DVDs, videos, electronics, computers, software, apparel &
What is ASCII?
characters in most of the computers that can be displayed on the computer screen... computers. IBM has its own built-in-code called EBCDIC code containing 256
What is Mobile Website
What is Mobile Website Mobile websites are specially designed for viewing mobile contents on Mobile Phones. Earlier websites were seen only on computers... very slower speed. So websites for computers cannot function well on mobile
PHP Is Great for Website Creation
PHP is one of the most commonly used and understood types of website creation scripts in the world. It is being used by all sorts of different computers and is being loaded onto many servers. Here are some reasons why PHP is so great
ASCII values table
ASCII values table          ASCII stands for American Standard Code for Information Interchange. Computers can only understand numbers, so an ASCII
Java for complete beginners
Java Guide is available at RoseIndia that help beginners to master the language. Because of its usefulness in both software development for computers and application development for mobile phone, Java is in great demand and so
Work Email- Dos and Don?ts
Work Email- Dos and Don’ts       Introduction With the proliferation of computers...; denotes using emails to vent emotions. With the fast pace of computers, it is very
Remote Desktop Setting in Windows 8
In windows 8 operating system you can easily access other computers inside the network by enabling the Remote Desktop Connection in your PC. 1... on the button before it.   5. Mark the 'Allow connections only from computers
EJB, Enterprise java bean, EJB Intoduction- Enterprise Java Beans (EJB) - An Introduction
of the system to be located on separate computers located in different locations... for servicing the clients in other computers. Object-oriented
Flex Mobile Phone Game Development
, iPhone, iPod, smart phones, mobile phones, computers, and on many gazettes
Top 10 Web Development Skills
of mobile devices that surpassed the traditional computers and devices as points
Windows 8 Operating System
Windows 8 is the latest innovation, which has been launched to make easy handling of the Windows operating system. Launched by the Microsoft it is expected to make easier for the use on personal computers and also for home and business
Intranet Application Development, Intranet Application Development Solutions, Intranet Design
Intranet Application Development Intranet Application Development Services India An intranet is a network of private computers linked together and using different web technologies to share the enterprise's
What is E-Commerce Web Design
conducting of business via Internet with the help of computers
 

 

 

DMCA.com