Tutorial: A Basic Calculator II

by
Ronald S. Holland
Total Application Works
RonHolland@sumtotalz.com • Tell a friend about this site (copy and paste the following HTML page into a file or send this page to a friend.)
<html>
<title>Example of a link </title>
<body>
<table border>
<a
href="http://www.sumtotalz.com/TotalAppsWorks/Calc_All/BasicCalc_Tut_II.html">

How to Create a Basic Calculator II Application </a>
</table>
</body>
</html>
Source
Screenshot
• On-site classes can be arranged in Java and C++. Send all inquiries to:
RonHolland@sumtotalz.com

• 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
• Method Summary
• Definitions

### Introduction

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

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 on the basic four-function calculator. 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. 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.
3. Use JButton for the numbers, functions, Exit, Help, and About.
4. Create a class to respond to the events caused by the numbers, functions, Exit, Help, and About buttons.

### Requirements for Basic Calculator II

1. +/- button: negates the sign of x.
2. Pow button: raises the value x to the power of y: xy.
3. 1/x button: divides the value of x into one.
4. Sqrt button: calculates the square root of the value of x.
5. CE button: clears the current value in the entry box.
6. CA button: clears all values (i.e., pending operations, and values except those in the M+ queue).
7. M+ button: loads values into a LIFO queue.
8. M- button: pops values from a LIFO queue.
9. n! button: calculates the factorial value of the number in the entry box.
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:

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

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
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.

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

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:

Figure 4: Automobile Template ``` class Toyota extends automobile { ... } class Avalon extends Toyota { ... } ```

This example is interpreted as class Avalon inherits from class Toyota and class Toyota inherits from class automobile. In the case of our calculator,

Figure 5: Basic Calculator class ``` 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:

Figure 6: Basic Calculator class Template ``` /** * The MyCalc class implements an application * and extends JFrame. */ class MyCalc extends JFrame { /** MyCalc constructor */ public MyCalc() { //initialization code super( "Simple Calculator" ); 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 */ MyCalc app = new MyCalc() ; } } ```

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

Figure 7: Calculator Title ``` super( "Simple 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:

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

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 8: The Layout for the Various Areas

In Figure 8, 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.

Figure 9: Add JTextField and textPanel ``` // adds the JTextField to the textPanel JTextField enterBox = new JTextField( 15 ) ; // adds the textPanel to JPanel textPanel = new JPanel() ; textPanel.add(enterBox ) ; // adds the textPanel to // the Container c North part c.add( textPanel , BorderLayout.NORTH ) ; ```

A code snippet showing how to use the GridLayout Manager follows.

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

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.

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

### Putting It Together: Build a Calculator

The structure for our calculator looks something like this:

Figure 12: Putting It Together: Build a Calculator ``` MyCalc +----------------------------------+ | | | +----------------------+ | | | actionPerformed() | | | +----------------------+ | | | MyCalc() | | | +----------------------+ | | | ConvertNumsToDouble()| | | +----------------------+ | | | divOp() | | | +----------------------+ | | | main() | | | +----------------------+ | | | multOp() | | | +----------------------+ | | | MyEqual() | | | +----------------------+ | | | MyFact() | | | +----------------------+ | | | MyMinus() | | | +----------------------+ | | | MyPrint( ) | | | +----------------------+ | | | MySqrt() | | | +----------------------+ | | | OneDivX() | | | +----------------------+ | | | opCodeMethod() | | | +----------------------+ | | | PlusMinus() | | | +----------------------+ | | | powerOp() | | | +----------------------+ | | | setResults() | | | +----------------------+ | | | setUpActionListener()| | | +----------------------+ | | | setUpButtons() | | | +----------------------+ | | | setUpExitPanel() | | | +----------------------+ | | | setUpFunctionPanel() | | | +----------------------+ | | | setup() | | | +----------------------+ | | | subOp() | | | +----------------------+ | | | sysExit() | | | +----------------------+ | | | +----------------------------------+ ```

• MyCalc() - constructor used for initialization
• main() - entry point for the application at run time
• actionPerformed() - This is the method that is called to respond to an event
• checkFirstNum() - checks for a number and ensures that it is not null
• ConvertNumsToDouble() - converts numbers entered from string to double
• divOp() - divides the two entered numbers and checks for a zero divisor
• multOp() - multiplies the two entered numbers
• MyPrint( ) - toggles debug aid on or off
• MySqrt() - computes the square root of the entered number
• OneDivX() - computes the value of one divided by the entered number
• opCodeMethod() - determines if there is a pending op to perform
• if so, that operation is performed
• if not, the current operation is performed
• PlusMinus() - toggles the sign of the entered number
• plusOp() - adds the two entered numbers
• powerOp() - raises the first number to the power of the second e.g., n1n2
• setResults() - enters the result of an operation in the textbox and the firstNum
• setup() - The setup() method is used to allocate the panel and button objects using the new function.
• subOp() - subtracts the second number from the first number
• sysExit() - causes the application to exit

### Method Summary

The following table shows the method summary. .

### Definitions

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.

Template - is a unique class or pattern that can be used to build other software code.

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