Java calculator


Published on

I made a calculator with using Menus and Button Array

Published in: Education
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Java calculator

  1. 1. Java CalculatorChapter 6<br />Sarah McNellis<br />
  2. 2. Entering Variables into the Calculator Application Code mean<br />Displays the code to begin the Calculator application. Lines 17 through 25 declare the private variables.<br />
  3. 3. Entering Variables into theCalculator Application<br />Import<br />Statements<br />import java.awt.*;<br />import java.awt.event.*;<br />import java.awt.datatransfer.*;<br />import java.text.DecimalFormat;<br />import javax.swing.JOptionPane;<br />public class Calculator extends Frame implements ActionListener<br />{<br /> private Button keys[];<br /> private Panel keypad;<br /> private TextField lcd;<br /> private double op1;<br /> private boolean first;<br /> private boolean foundKey;<br /> private boolean clearText;<br /> private int lastOp;<br /> private DecimalFormat calcPattern;<br />Class<br />Header<br />Private <br />Variables<br />Declared<br />
  4. 4. Using Menus in the Calculator Application code means <br />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<br />
  5. 5. Using Menus in the Calculator Application<br />Constructor<br />Method header<br />public Calculator()<br />{<br /> // create an instance of the menu<br /> MenuBar mnubar = new MenuBar();<br /> setMenuBar(mnuBar);<br /> // construct and populate the File Menu<br /> Menu mnuFile = new Menu("File", true);<br /> setMenuBar(mnuBar);<br /> MenuItem mnuFileExit = new MenuItem("Exit");<br /> mnuFile.and(mnuFileExit);<br />Code to create <br />Menu bar<br />Code to create <br />File menu<br />
  6. 6. Using Menus in the Calculator Application Continue<br />// construct and populate the Edit menu<br /> Menu mnuEdit = new Menu("Edit", true);<br /> mnuBar.and(mnuEdit);<br /> MenuItem mnuEditClear = new MenuItem("Clear");<br /> mnuEdit.and(mnuEditClear);<br /> mnuEdit.insertSeparator(1);<br /> MenuItem mnuEditCopy = new MenuItem("Copy");<br /> mnuEdit.and(mnuEditCopy);<br /> MenuItem mnuEditPaste = new MenuItem("Paste");<br /> mnuEdit.and(mnuEditPaste);<br /> // construct and populate the About menu<br /> Menu mnuAbout = new Menu("About", true);<br /> mnuBar.and(mnuAbout);<br /> MenuItem mnuAboutCalculator = new MenuItem("About Calculator");<br /> mnuAbout.add(mnuAboutCalculator);<br />Code to create<br />Edit menu<br />Code to create<br />About menu<br />
  7. 7. Using Menus in the Calculator Application Continue<br />// add the ActionListener to each menu item<br />mnuFileExit.addActionListener(this);<br />mnuEditClear.addActionListener(this);<br />mnuEditCopy.addActionListener(this);<br />mnuEditPaste.addActionListener(this);<br />mnuAboutCalculator.addActionListener(this);<br />// assign an ActionCommand to each menu item<br />mnuFileExit.setActionCommand("Exit");<br />mnuEditClear.setActionCommand("Clear");<br />mnuEditCopy.setActionCommand("Copy");<br />mnuEditPaste.setActionCommand("Paste");<br />mnuAboutCalculator.setActionCommand("About");<br />addActionListener() <br />Methods for each menu item<br />setActionCommand() methods for each menu item<br />
  8. 8. Initializing the Calculator Variables code means<br />It display the code to set initial values for the Calculator application.<br />
  9. 9. Initializing the Calculator Variables<br />// construct components and initialize beginning values<br />lcd = new TextField(20);<br /> lcd.setEditable(false);<br />keypad = new Panel();<br />keys = new Button[16];<br />first = true;<br />op1 = 0.0;<br />clearText = true;<br />lastOp= 0;<br />calcPattern = new DecimalFormat("########.########");<br />Code to initialize variables<br />
  10. 10. Creating the Keypad code means<br />Displays the code to construct and label the keypad buttons, as well as the method to establish the GridLayout to organize the buttons.<br />
  11. 11. Creating the Keypad<br />// construct and assign captions to the Buttons<br />for (int i=0; i<=9; i++)<br /> key[i] = new Button(String.valueOf(i));<br />keys[10] = new Button("/");<br />keys[11] = new Button("*");<br />keys[12] = new Button("-");<br />keys[13] = new Button("+");<br />keys[14] = new Button("=");<br />keys[15] = new Button(".");<br />// set Frame and keypad layout to grid layout<br />setLayout(new BorderLayout());<br />keypad.setLayout(new GridLayout(4,4,10,10));<br />Code to construct<br />Buttons using array<br />setLayout() methods set BorderLayout for Frame and GridLayout for keypad<br />
  12. 12. Adding components to the interface code means<br />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.<br />
  13. 13. Adding components to the interface<br />for (int i=7; i<=10; i++) // 7, 8, 9, divide<br /> keypad.add(keys[i]);<br />for (int i=4; i<=6; i++) // 4, 5, 6<br /> keypad.add(keys[i]);<br /> keypad.add(keys[11]); // multiply<br />for (int i=1; i<=3; i++) // 1, 2, 3<br /> keypad.add(keys[i]);<br /> keypad.add(keys[12]); // subtract<br /> keypad.add(keys[0]); // 0 key<br />for (int i=15; i>=13; i--)<br /> keypad.add(keys[i]); // decimal point, =, add (+) keys<br />Code to add buttons keypad<br />
  14. 14. Continuation of adding components to the Interface code means<br />It displays the code to add the ActionListener to each of the Buttons.<br />
  15. 15. Continue adding componentsto the Interface<br />Code to add<br />Buttons to keypad<br />for (int i=0; i<keys.length; i++)<br /> keys[i].addActionListener(this);<br />add(lcd, BorderLayout.NORTH);<br />add(keypad, BorderLayout.CENTER);<br />Lcd TextField and <br />keypad Panel components<br />Added to frame<br />
  16. 16. Coding the addWindowListenerMethod means<br />It displays the code to add a WindowListener for the Frame<br />
  17. 17. Coding the addWindowListenerMethod<br />Creates occurrence<br />Of windowAdapter()<br />class<br />addWindowListener(<br /> new WindowAdapter()<br /> {<br /> public void windowClosing(WindowEvent e)<br /> {<br /> System.exit(0);<br /> }<br /> }<br /> );<br />}// end of constructor method<br />addWindowListener()<br />method<br />Overrides <br />windowClosing()<br />method<br />Brace to add method<br />
  18. 18. Searching for the Exitand Clear Commands code means<br />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.<br />
  19. 19. Searching for the Exitand Clear Commands<br />ActionPerformed()<br />Method header<br />public void actionPerformed(ActionEvent e)<br /> {<br /> //test for menu item clicks<br /> String arg = e.getActionCommand();<br /> if (arg == "Exit")<br /> System.exit(0);<br /> if (arg == "Clear")<br /> {<br /> clearText = true;<br /> first = true;<br /> op1 = 0.0;<br /> lcd.setText("")<br /> lcd.requestFocus();<br /> }<br />Tests<br />For Exit<br />command<br />Code to exit<br />program<br />Tests for<br />Clear<br />command<br />Code to clear<br />Number displayed in<br />Lcd TextField and<br />Reset initial values<br />
  20. 20. Searching for the Copy and Paste Commands code means<br />It displays the code executed if the user clicks Copy or Paste on the Edit menu.<br />
  21. 21. Searching for the Copy and Paste Commands Code<br />Tests if Copy <br />Command clicked<br />if (arg == "Copy")<br />{<br />Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard();<br />StringSelection centents = new StringSelection(lcd.getText());<br />cb.setContents(contents, null);<br />}<br />if (arg == "Paste")<br />{<br />Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard();<br />Transferable content = cb.getContents(this);<br />try<br />{<br />String s = (String)content.getTransferData(DataFlavor.stringFlavor);<br />lcd.setText(calcPattern.format(Double.parseDouble(s)));<br />}<br />catch (Throwable exc)<br />{<br />lcd.setText("")<br />}<br />}<br />Code to copy display<br />To clipboard<br />Test if Paste command<br />clicked<br />Code to paste data <br />From clipboard<br />
  22. 22. Searching for the About Calculator Command mean in code<br />It display the code to search for the Calculator command.<br />
  23. 23. Searching for the About Calculator Command Code<br />Test if the About<br />Command was clicked<br />if (arg == "About")<br /> {<br /> String message = "Calculator ver. 1.0nOpenExhibit SoftwarenCopyright 2007nAll right reserved";<br /> JOptionPane.showMessageDialog(null ,message,"About Calculator", JOptionPane.INFORMATION_MESSAGE);<br /> }<br />Code to display <br />About Calculator<br />Message box<br />
  24. 24. Searching the Numeric Buttons Code means<br />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.<br />
  25. 25. Searching the Numeric Buttons Code<br />// test for button clicks<br /> foundKey = false;<br />// search for the clicked key<br />for (int i=0; i<keys.length && !foundKey; i++)<br />{<br />if(e.getSource() == keys[i])<br />{<br />foundKey = true;<br />switch(i)<br /> {<br />// number and decimal point buttons<br />case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 8: case 9: case 15:<br />if(clearText)<br />{<br />lcd.setText("");<br />clearText = false;<br />}<br />lcd.setText(lcd.getText() + keys[i].getLabel());<br />break;<br />It displays the code<br />To test for button click<br />Of the numeric<br />Buttons or the <br />Decimal point button<br />
  26. 26. Searching for the First Operator ButtonClick Code means<br />It displays the code to search the array and add functionality to the operator buttons within the actionPerformed() method.<br />
  27. 27. Searching for the First Operator ButtonClick Code<br />// operator buttons<br />case 10: case 11: case 12: case 13: case 14:<br />clearText = true;<br />if (first) // first operand<br />{<br />if(lcd.getText().length()==0) op1 = 0.0;<br />else op1 = Double.parseDouble(lcd.getText());<br /> first = false;<br /> clearText = true;<br /> lastOp = i; //save last operator<br />}<br />It displays the code to <br />Handle the first operator<br />Button click in a <br />calculation<br />
  28. 28. Searching for Subsequent OperatorClicks code means<br />This displays is the code that executes on subsequent operator click<br />
  29. 29. Searching for Subsequent OperatorClicks code<br />else // second operand<br />{<br />switch(lastOp)<br />{<br />case 10: // divide button<br />op1 /= Double.parseDouble(lcd.getText());<br />break;<br />case 11: // multiply button<br />op1 *= Double.parseDouble(lcd.getText());<br />break;<br />case 12: // minus button<br />op1 -= Double.parseDouble(lcd.getText());<br />break;<br />case 13: // plus button<br />op1 += Double.parseDouble(lcd.getText());<br />break;<br />} // end of switch(lastOp)<br />lcd.setText(calcPattern.format(op1));<br />clearText = true;<br />The code to handle<br />Subsequent operator<br />Button click in a calculation<br />
  30. 30. Searching for the Equal Button code means<br />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.<br />
  31. 31. Searching for the Equal Button code<br />The cod to handle a click of <br />The equal button, <br />Represented by the subscript<br />14 in the array.<br />if(i==14) first = true;//equal button<br />else lastOp = i; // save last operator<br />} // end else<br />break;<br />} // end of switch(i)<br />} // end of if<br />} // end of for<br />} // end of actionPerformed<br />
  32. 32. Coding the main() Method for the Calculator class coding means<br />The main() method for the Calculator application constructs an instance of the Calculator class and then sets three attributes.<br />
  33. 33. Coding the main() Method for the Calculator class<br />public static void main(String args[])<br />{<br />// set frame properties<br />Calculator f = new Calculator();<br />f.setTitle("Calculator Application");<br />f.setBounds(200,200,300,300);<br />f.setVisible(true);<br />// set image properties and add to frame<br />Image icon = Toolkit.getDefaultToolkit().getImage("calcImage.gif");<br />f.setIconImage(icon);<br />} // end of main<br />}// end of class<br />
  34. 34. Print screen of the Calculator<br />
  35. 35. Link to the file<br />Calculator<br />
  36. 36. Work Cited<br />Shelly Cashman Starks Mick: “Java Programming comprehensive Concepts and Techniques” third Edition print 2006<br />