java calculator

36
Java Calculator Chapter 6 Sarah McNellis

Upload: sarah-mcnellis

Post on 23-Dec-2014

4.229 views

Category:

Education


1 download

DESCRIPTION

I made a calculator with using Menus and Button Array

TRANSCRIPT

Page 1: Java calculator

Java CalculatorChapter 6

Sarah McNellis

Page 2: Java calculator

Entering Variables into the Calculator Application Code mean

Displays the code to begin the Calculator application. Lines 17 through 25 declare the private variables.

Page 3: Java calculator

Entering Variables into theCalculator Application import java.awt.*; import java.awt.event.*; import java.awt.datatransfer.*; import java.text.DecimalFormat; import javax.swing.JOptionPane;

public class Calculator extends Frame implements ActionListener

{ private Button keys[]; private Panel keypad; private TextField lcd; private double op1; private boolean first; private boolean foundKey; private boolean clearText; private int lastOp; private DecimalFormat

calcPattern;

ImportStatements

ClassHeader

Private VariablesDeclared

Page 4: Java calculator

Using Menus in the Calculator Application code means

Displays the beginning of the Calculator() constructor method also the code in the slide also shows the code that to set up the menu system. These are some of the meaning of the codes

Page 5: Java calculator

Using Menus in the Calculator Application

public Calculator() { // create an instance of the menu MenuBar mnubar = new MenuBar(); setMenuBar(mnuBar); // construct and populate the File Menu Menu mnuFile = new Menu("File", true); setMenuBar(mnuBar); MenuItem mnuFileExit = new

MenuItem("Exit"); mnuFile.and(mnuFileExit);

ConstructorMethod header

Code to create Menu bar

Code to create File menu

Page 6: Java calculator

Using Menus in the Calculator Application Continue // construct and populate the Edit menu Menu mnuEdit = new Menu("Edit", true); mnuBar.and(mnuEdit); MenuItem mnuEditClear = new

MenuItem("Clear"); mnuEdit.and(mnuEditClear); mnuEdit.insertSeparator(1); MenuItem mnuEditCopy = new

MenuItem("Copy"); mnuEdit.and(mnuEditCopy); MenuItem mnuEditPaste = new

MenuItem("Paste"); mnuEdit.and(mnuEditPaste);

// construct and populate the About menu Menu mnuAbout = new Menu("About", true); mnuBar.and(mnuAbout); MenuItem mnuAboutCalculator = new

MenuItem("About Calculator"); mnuAbout.add(mnuAboutCalculator);

Code to createAbout menu

Code to createEdit menu

Page 7: Java calculator

Using Menus in the Calculator Application Continue // add the ActionListener to each menu item mnuFileExit.addActionListener(this); mnuEditClear.addActionListener(this); mnuEditCopy.addActionListener(this); mnuEditPaste.addActionListener(this); mnuAboutCalculator.addActionListener(this);

// assign an ActionCommand to each menu item mnuFileExit.setActionCommand("Exit"); mnuEditClear.setActionCommand("Clear"); mnuEditCopy.setActionCommand("Copy"); mnuEditPaste.setActionCommand("Paste"); mnuAboutCalculator.setActionCommand("About");

addActionListener() Methods for each

menu item

setActionCommand() methods for each

menu item

Page 8: Java calculator

Initializing the Calculator Variables code means

It display the code to set initial values for the Calculator application.

Page 9: Java calculator

Initializing the Calculator Variables

// construct components and initialize beginning values

lcd = new TextField(20); lcd.setEditable(false); keypad = new Panel(); keys = new Button[16]; first = true; op1 = 0.0; clearText = true; lastOp= 0; calcPattern = new

DecimalFormat("########.########");

Code to initialize variables

Page 10: Java calculator

Creating the Keypad code means

Displays the code to construct and label the keypad buttons, as well as the method to establish the GridLayout to organize the buttons.

Page 11: Java calculator

Creating the Keypad

// construct and assign captions to the Buttons for (int i=0; i<=9; i++) key[i] = new

Button(String.valueOf(i));

keys[10] = new Button("/"); keys[11] = new Button("*"); keys[12] = new Button("-"); keys[13] = new Button("+"); keys[14] = new Button("="); keys[15] = new Button(".");

// set Frame and keypad layout to grid layout setLayout(new BorderLayout()); keypad.setLayout(new

GridLayout(4,4,10,10));

Code to constructButtons using array

setLayout() methods set BorderLayout for Frame and GridLayout for keypad

Page 12: Java calculator

Adding components to the interface code means

Displays the code to add the 16 buttons to the panel using the four-row, four-column grid. Line comments within the code will help you understand how each loop and add method takes its turn creating buttons in the keypad.

Page 13: Java calculator

Adding components to the interface

for (int i=7; i<=10; i++) // 7, 8, 9, divide keypad.add(keys[i]);

for (int i=4; i<=6; i++) // 4, 5, 6 keypad.add(keys[i]);

keypad.add(keys[11]); // multiply for (int i=1; i<=3; i++) // 1, 2, 3 keypad.add(keys[i]); keypad.add(keys[12]); // subtract keypad.add(keys[0]); // 0 key for (int i=15; i>=13; i--) keypad.add(keys[i]); // decimal point, =, add (+)

keys

Code to add buttons keypad

Page 14: Java calculator

Continuation of adding components to the Interface code means

It displays the code to add the ActionListener to each of the Buttons.

Page 15: Java calculator

Continue adding componentsto the Interface

for (int i=0; i<keys.length; i++)

keys[i].addActionListener(this); add(lcd, BorderLayout.NORTH); add(keypad, BorderLayout.CENTER);

Lcd TextField and keypad Panel components

Added to frame

Code to addButtons to keypad

Page 16: Java calculator

Coding the addWindowListenerMethod means

It displays the code to add a WindowListener for the Frame

Page 17: Java calculator

Coding the addWindowListenerMethod

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

}// end of constructor method

Creates occurrenceOf windowAdapter()

class

Overrides windowClosing()

method

addWindowListener()method

Brace to add method

Page 18: Java calculator

Searching for the Exitand Clear Commands code means

Displays the code used to search to menu items for a click. During program execution, the ActionCommand of any click in the interface, menu, or button will be stored in the variable arg.

Page 19: Java calculator

Searching for the Exitand Clear Commands

public void actionPerformed(ActionEvent e) { //test for menu item clicks String arg =

e.getActionCommand(); if (arg == "Exit") System.exit(0); if (arg == "Clear") { clearText = true; first = true; op1 = 0.0; lcd.setText("") lcd.requestFocus(); }

ActionPerformed()Method header

Code to exitprogram

Code to clearNumber displayed in

Lcd TextField andReset initial values

TestsFor Exit

command

Tests

for

Clear

command

Page 20: Java calculator

Searching for the Copy and Paste Commands code means

It displays the code executed if the user clicks Copy or Paste on the Edit menu.

Page 21: Java calculator

Searching for the Copy and Paste Commands Code if (arg == "Copy") { Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard(); StringSelection centents = new StringSelection(lcd.getText()); cb.setContents(contents, null); } if (arg == "Paste") { Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard(); Transferable content = cb.getContents(this); try { String s = (String)content.getTransferData(DataFlavor.stringFlavor); lcd.setText(calcPattern.format(Double.parseDouble(s))); } catch (Throwable exc) { lcd.setText("") } }

Tests if Copy Command clicked

Code to copy displayTo clipboard

Test if Paste commandclicked

Code to paste data From clipboard

Page 22: Java calculator

Searching for the About Calculator Command mean in code

It display the code to search for the Calculator command.

Page 23: Java calculator

Searching for the About Calculator Command Code if (arg == "About") { String

message = "Calculator ver. 1.0\nOpenExhibit Software\nCopyright 2007\nAll right reserved";

JOptionPane.showMessageDialog(null ,message,"About Calculator", JOptionPane.INFORMATION_MESSAGE);

}

Test if the AboutCommand was clicked

Code to display About Calculator

Message box

Page 24: Java calculator

Searching the Numeric Buttons Code means

It displays the code to search the array of buttons to determine which button the user clicked and to add functionality to the numeric buttons and the decimal point in the actionPerformed() method.

Page 25: Java calculator

Searching the Numeric Buttons Code // test for button clicks

foundKey = false; // search for the clicked key for (int i=0; i<keys.length && !foundKey; i++) { if(e.getSource() == keys[i]) { foundKey = true; switch(i) { // number and decimal point buttons case 0: case 1: case 2: case 3: case 4: case 5: case 6:

case 7: case 8: case 9: case 15: if(clearText) { lcd.setText(""); clearText = false; } lcd.setText(lcd.getText() + keys[i].getLabel()); break;

It displays the codeTo test for button click

Of the numericButtons or the

Decimal point button

Page 26: Java calculator

Searching for the First Operator ButtonClick Code means

It displays the code to search the array and add functionality to the operator buttons within the actionPerformed() method.

Page 27: Java calculator

Searching for the First Operator ButtonClick Code // operator buttons case 10: case 11: case 12: case 13:

case 14: clearText = true;

if (first) // first operand { if(lcd.getText().length()==0) op1 = 0.0; else op1 =

Double.parseDouble(lcd.getText()); first = false; clearText = true; lastOp = i; //save last operator }

It displays the code to Handle the first operator

Button click in a calculation

Page 28: Java calculator

Searching for Subsequent OperatorClicks code means

This displays is the code that executes on subsequent operator click

Page 29: Java calculator

Searching for Subsequent OperatorClicks code else // second operand { switch(lastOp) { case 10: // divide button op1 /= Double.parseDouble(lcd.getText()); break; case 11: // multiply button op1 *= Double.parseDouble(lcd.getText()); break; case 12: // minus button op1 -= Double.parseDouble(lcd.getText()); break; case 13: // plus button op1 += Double.parseDouble(lcd.getText()); break; } // end of switch(lastOp) lcd.setText(calcPattern.format(op1)); clearText = true;

The code to handleSubsequent operator

Button click in a calculation

Page 30: Java calculator

Searching for the Equal Button code means

When the user specifically clicks the equal button, the lastOp variable is assigned a value of 14, which is the index number of the equal button.

Page 31: Java calculator

Searching for the Equal Button code

if(i==14) first = true;//equal button

else lastOp = i; // save last operator

} // end elsebreak;} // end of switch(i)} // end of if} // end of for} // end of actionPerformed

The cod to handle a click of The equal button,

Represented by the subscript14 in the array.

Page 32: Java calculator

Coding the main() Method for the Calculator class coding means

The main() method for the Calculator application constructs an instance of the Calculator class and then sets three attributes.

Page 33: Java calculator

Coding the main() Method for the Calculator class public static void main(String args[]) { // set frame properties Calculator f = new Calculator(); f.setTitle("Calculator Application"); f.setBounds(200,200,300,300); f.setVisible(true);

// set image properties and add to frame Image icon = Toolkit.getDefaultToolkit().getImage("calcImage.gif"); f.setIconImage(icon);

} // end of main }// end of class

Page 34: Java calculator

Print screen of the Calculator

Page 35: Java calculator

Link to the file

Calculator

Page 36: Java calculator

Work Cited

Shelly Cashman Starks Mick: “Java Programming comprehensive Concepts and Techniques” third Edition print 2006