Tutorial: A Basic Calculator


by
Ronald S. Holland
Total Application Works
RonHolland@sumtotalz.com






To visit my site

HOME] Consulting Design Maintenance Project Testing Training Turnkey Java C++ SQL HTML JavaScript ]


To contact us

© 2002 - 2016 All Rights Reserved Total Application Works


  • Tell a friend about this site (copy and paste the following URL or send this page to a friend.)
  • <html>
    <title>Example of a link </title>
    <body>
    <table border>
    <a href="http://sumtotalz.com/TotalAppsWorks/Calc_All/BasicCalc_Tut.html"> A Basic Calculator Tutorial </a>
    </table>
    </body>
    </html>
  • On-site classes can be arranged in Java and C++. Send all inquiries to:
  • RonHolland@sumtotalz.com
  1. Java Table of contents
  2. 2nd Java Cup
  3. Pie Chart I
  4. Pie/Bar Chart IB
  5. Pie/Bar Chart II
  6. Pie/Bar Chart III
  7. A Basic Calculator
  8. Linked Lists
  9. Linked List II
  10. Linked List III
  11. Linked List IV
  12. Hardware Store I
  13. Hardware Store II
  14. Hardware Store III
  15. Client/Server
  16. Client/Server II
  17. Client/Server III
  18. Client/Server IV
  19. Multithreaded Client/Server
  20. Multithreaded Client/Server II
  21. Multithreaded Client/Server III
  22. Basic Calculator II
  23. Basic Calculator III
  • Introduction
  • Requirements
  • What is the Holland's OOP Programming Design Model?
  • Application Template
  • Let's Expand on Our Template
  • The setup() Method
  • Event Handlers
  • Putting It Together: Build a Calculator

    Introduction

    This tutorial assumes that you have read and completed the following two tutorials.

    1. Your First Cup of Java
    2. Getting Started
    3. A basic java program .
    4. A basic Calculator using Swing II for a more advanced tutorial on how to build a calculator.
    The rest of this tutorial will build on and reinforce what you learned from the above tutorials. This tutorial will expand on:
    1. JButton
    2. JPanel
    3. JTextField
    4. Container
    5. String

    In addition, this tutorial assumes that you understand templates. In this tutorial we will build a basic four-function calculator, with minimal error checking. The calculator that we build will look like:

    Figure 1: Basic Calculator

    Requirements

    The requirements for the task are:

    1. Build a calculator application, using the application template.
    2. Also use Holland's OOP Programming Design Model to build the calculator.
    3. Build a four function calculator with the following functions:
      • Addition - adds two numbers: n1 + n2.
      • Subtraction - subtracts number two from number one: n1 - n2.
      • Multiplication - Multiplies two numbers: n1 * n2.
      • Division - divides number two into number one: n1 / n2.
      • Provide minimal error checking, in order to keep the code less complex.
    4. Use JTextField to hold the data that the user enters.
    5. Use JButton for the numbers, functions, Exit, Help, and About.
    6. Create a class to respond to the events caused by the numbers, functions, Exit, Help, and About buttons.
    In the next section, we will explore Holland's OOP Programming Design Model.

    What is the Holland's OOP Programming Design Model?

    In object-oriented programming, programming revolves around the data. So in this style, the top is the data. It might be depicted as follows:

      
              +--------------+
              |      Data    |<----+  
              +-------+------+     | 
                      ^            |
                      |----------->+
                      V            ^
              +-------+------+     |
              |   Top-down   |     | 
              |  Structured  |<----+
              |  programming |     |
              |  on Classes  |     | (step-wise)
              |  and methods |     | (refinement)
              +--------------+     | (as needed) 
                      |            |
                      +------------+ 
     
      
    Figure 2: Holland's OOP Programming Design Model


    The data is entered in the Display box (JTextField) on the calculator, using the pushbuttons with numbers and/or a dot on it. This data is operated on in a binary (two numbers) fashion or in a unary (one number) fashion. The calculator operates in a

    1. binary (two numbers)
      • Multiplication
      • Division
      • Subtraction
      • Addition
    2. unary (one number) fashion
      • Plus/Minus
    3. Application functions
      • Clear
      • Clear Entry
      • Exit
    4. Equals sign displays the result of binary and/or unary operations.
    5. The pressing of the pushbuttons will result in an event handler (method) responding to the event.
      • Button Clear Entry Pressed
      • Button Clear Pressed
      • Button Plus Pressed
      • Button Minus Pressed
      • Button Multiplication Pressed
      • Button Division Pressed
      • Button Exit Pressed
      • Button Help Pressed
      • Button About Pressed
    In the next section, I will describe how to build the calculator template.

    Application Template

    We are going modify the template used in the Second Cup of Coffee by having it extend the JFrame class.

      
    /** 
     * The BasicCalc class implements an application
     * and extends JFrame.
     */
    class BasicCalc extends JFrame {
    
        /** BasicCalc constructor */
        public BasicCalc() {
           initialization code
           ...
        } 
    
        public static void main(String[] args) {
                  /** creates an instance of BasicCalc  */
            BasicCalc app = new BasicCalc() ; 
        }
    }
      
    Figure 3: Application Template


    Let's consider the class of automobile, which contains the set of all automobiles. A sampling might be:

    • Acura TL
    • BMW 5 series
    • Buick Century
    • Ford Explorer
    • Honda Pilot
    • Mazda6
    • Toyota Avalon
    • Toyota Highlander
    • Volvo S60
    • etc.
    If we were to write one of the examples above in Java, it might look like:

      
    class Toyota extends automobile {
       ...
    }
    
    class Avalon extends Toyota {
       ...
    }
      
    Figure 4: automobile inheritance


    This example is interpreted as class Avalon inherits from class Toyota and class Toyota inherits from class automobile. In the case of our calculator,
      
    class BasicCalc extends JFrame {
      
    BasicCalc inherits from JFrame. A more detailed discussion of inheritance is beyond the scope of this tutorial. You can find a write-up on inheritance at sun.com.

    Let's Expand on Our Template

    In many textbooks, these beginning sections start off with much of the initialization taking place in the main() method. In reality, much of the initialization takes place in a piece of code called a constructor. A constructor is a method that has the same name as the class. At this point our application template looks like:

      
      
    /** 
     * The BasicCalc class implements an application 
     * and extends JFrame.
     */
    class BasicCalc extends JFrame {
    
        /** BasicCalc constructor */
        public BasicCalc() {
    
          super( "Basic Calculator" );
          //initialization code
          setup() ;
    
               /** sets the size of the frame */
          setSize( 350, 300 ); 
               /** sets the location of the frame on the screen*/
          setLocation( 200, 200 ) ; 
              /** makes the frame visible */      
          show();                
        } 
    
        public static void main(String[] args) {
               /** creates an instance of BasicCalc  */
            BasicCalc app = new BasicCalc() ; 
        }
    }  
      
    Figure 5: expanced template


    where the method setup() has the majority of the initialization code. A line of interest is the following:

      
    super( "Basic Calculator" );
      
    This line is a call to the parent class' constructor. In this case, it is a call to JFrame's constructor with the title for the frame.

    The setup() Method

    When we are considering adding graphics to a frame, we need an anchor (context) that we can use as a reference for all of the graphics. The display area for a JFrame has a context, called a content pane to which the graphics must be attached if they are to be displayed at run time. To get the context in Java, we write a line similar to:

      
             // get the context or content pane
    Container c = getContentPane(); 
      

    We are at a design point. We need to lay out the graphics in a precise order. Specifically, we need to have

    • One graphic at the top (North);
    • Four rows in the middle, with each containing three graphics (Center);
    • One row at the bottom containing three graphics (South);
    • Four rows on the right, with each containing one graphic (East);
    With this lay out, our grouping would look like:

    Figure 6: The Layout for the Various Areas

    In Figure 6, 1x3 means that there is one row with three graphics in that row. We will use a Layout Manager to group our graphics. However, there is a problem. We can have only one Layout Manager per Container. How do we solve this problem? A Container can contain other Containers. Complex GUIs that require that each component be placed in an exact location usually consist of multiple containers called JPanels.

    We will use two different Layout Managers to accomplish our goals. We will use the BorderLayout Manager to place the JPanels in the appropriate areas and the GridLayout Manager for rows and columns. For example, to create a JTextField and a JPanel and then add them to the Container c follows.

      
    JTextField enterBox  = new JTextField( 15 ) ;
    JPanel textPanel = new JPanel() ;
         // adds the JTextField to the textPanel
    textPanel.add(enterBox ) ;   
         // adds the textPanel to the Container c North
    c.add( textPanel , BorderLayout.NORTH ) ; 
                                              
      
    A code snippet showing how to use the GridLayout Manager follows.

      
    buttonPanel = new JPanel() ;
    c.add( buttonPanel , BorderLayout.CENTER ) ;
    
    JButton bZero   = new JButton( "0" ) ;
    
    buttonPanel.add( bZero ) ;
    
    buttonPanel.setLayout( new GridLayout( 5, 3, 5, 5  ) );
      
    Figure 7: GridLayout Manager example


    We can use these code examples to layout the face of the calculator. Next we need to write the code that responds to a button being pressed.

    Event Handlers

    When a button is pressed, it is called and event. The code that responds to this event is called an event handler. In the event handler, there is code to perform the appropriate task in response to the event. For example, suppose the zero button is pressed. The following code is an example of what happens.

      
    public void actionPerformed( ActionEvent e )    {
       if ( e.getSource() == bZero ) {
          enterBox.setText( enterBox.getText() + "0" ) ;
       }
    }
      
    Figure 8: Event Handlers


    Putting It Together: Build a Calculator

    The structure for our calculator looks something like this:

      
    class BasicCalc
    +----------------------------------+
    |                                  |
    |  +------------------------+      |
    |  | BasicCalc() constructor|      |
    |  +------------------------+      |
    |  | setUpTextField() method|      |
    |  +------------------------+      |
    |  | setUpButtons() method  |      |
    |  +------------------------+      |
    |  | setUpFunctionPanel()   |      |
    |  |     method             |      |
    |  +------------------------+      |
    |  | setUpExitPanel()       |      |
    |  |     method             |      |
    |  +------------------------+      |
    |  | setUpActionListener()  |      |
    |  |     method             |      |
    |  +------------------------+      |
    |  | main() method          |      |
    |  +------------------------+      |
    |  | actionPerformed()      |      |
    |  |     method             |      |
    |  +------------------------+      |
    |  | ConvertNumsToDouble()  |      | 
    |  |     method             |      |    
    |  +------------------------+      |
    |  | divOp()  method        |      |     
    |  +------------------------+      |
    |  | getFirstNum( )         |      |  
    |  |     method             |      |      
    |  +------------------------+      |
    |  | multOp() method        |      |     
    |  +------------------------+      |
    |  | MyPrint( ) method      |      |     
    |  +------------------------+      |
    |  | opCodeMethod()         |      | 
    |  |     method             |      |       
    |  +------------------------+      |
    |  | plusOp() method        |      |     
    |  +------------------------+      |
    |  | setResults() method    |      |     
    |  +------------------------+      |
    |  | setup() method         |      |     
    |  +------------------------+      |
    |  | subOp() method         |      |     
    |  +------------------------+      |
    |  | sysExit() method       |      |     
    |  +------------------------+      |
    |                                  |  
    +----------------------------------+
    
    
      
    Figure 9: class BasicCalc Layout


    BorderLayout - A border layout lays out a container, arranging and resizing its components to fit in five regions: north, south, east, west, and center.

    extends - when considering class MyClass extends ParentClass, MyClass inherits from ParentClass. Java does not support multiple inheritance; it supports only single inheritance.

    Container - A generic Abstract Window Toolkit(AWT) container object is a component that can contain other AWT components.

    GridLayout - Creates a grid layout with a default of one column per component, in a single row.

    JFrame - A JFrame is a top-level window with a title and a border.

    JPanel - is a generic lightweight container.

    Layout Manager - Defines the interface for classes that know how to layout objects in Containers.




  • [
    HOME] Consulting Design Maintenance Project Testing Training Turnkey Java C++ SQL HTML JavaScript ]

    © 2002 - 2016 All Rights Reserved Total Application Works