Homework 6

Java Applets and Calculator Class

Modified

Java applet Overview

Java was designed to support applications distributed across the Internet. These applications are called applets and are typically executed by a Web browser such as Netscape capable of executing Java code. A complete applet consists of a Java class that is the actual applet executable and an HTML (HyperText Markup Language) file with instructions to the browser to execute the Java applet class.

Calculator Overview

Consider the design of a simple four-function calculator. Visually, a calculator consists of a user interface containing a few buttons and a readout display. The calculator is then a user interface with internal accumulator that holds numbers as they're entered, displayed and used also as an operand in arithmetic. Binary operations using infix notation for expressions, 45 + 73 = for example, save the accumulator, 45, when '+' is entered, then store 73 to accumulator. When the '=' is pressed the earlier '+' operation is performed, so the + operation must be stored for use later when the '=' is pressed. The result of the arithmetic is stored back to accumulator for display and use in later calculations.

Calculator
         12.34
1  2  3  +  -
4  5  6  *  /
7  8  9  0  =
CR

HW6 HTML

The minimal HW6.htm HTML file for executing the HW6 applet is:

HW6.htm
<APPLET code="HW6.class" width=100 height=100>
</APPLET>

which notifies the browser that HW6.class should be loaded from the same location as the HTML file. Click to run HW6 as completed below. Test by entering 1+11=.

HW6 class

The HW6 class serves to test each of the assignments; in this case HW6 inherits from class Calculator which obviously provides all the functionality (HW6 does nothing but invoke the default Calculator constructor). Class HW6 is not needed other than to define the public HW6 class used in the HW6.htm file for execution.

HW6.java
public class HW6 extends Calculator { }

The following assignments extend Calculator class, change the class Calculator to the name of the class being tested (e.g. MemoryCalculator, etc.)

Calculator class

The Calculator adds addition, subtraction, multiplication, and division calculation to a UserInterface class which defines the user interface display and keypad. A Calculator must maintain state of an accumulator, operand, and operation to perform binary arithmetic. Notice that input of  42-15= must produce the following:

42     accumulator = 42
-      operation = -, operand = accumulator
15     accumulator = 15
=      accumulator = operand operation accumulator (i.e. 42-15)

The purpose and special notes of each Calculator method are:

Calculator.java
public class Calculator extends UserInterface
 {
         private double accumulator=0.0, operand;
         private char   operation;
         
         public Calculator()
         {       
                 addButton("1");
                 addButton("+");
                 addButton("=");
         }

         public void onClick(char c)
         {       switch (c) {
                         case '1' : accumulator = accumulator * 10+1;
                                       break;
                         case '=' : equal();
                                       break;
                         case '+' : operation = c;
                                       operand = accumulator;
                                       accumulator = 0.0;
                                       break;
                         default  : ;
                 }
                 updateDisplay(getAccumulator()+"");
         }

         public void equal()
         {       switch (operation)
                 {       case '+' : accumulator = accumulator + operand;
                                        break;
                 }
         }

         public double getAccumulator() { return accumulator; }
         public void     setAccumulator(double acc) { accumulator = acc; }
         public double getOperand() { return operand;}
         public void     setOperand(double newOperand) { operand = newOperand;}
         public char     getOperation() { return operation; }
         public void     setOperation(char newOperation ) { operation = newOperation; }
}

UserInterface class

The complete graphical user interface is implemented in the abstract UserInterface class; an abstract class can only be inherited (i.e. extended), no objects of that class can be created. The class defines two user interface objects, a display on which to display text and visible buttons, and handle mouse clicking by invoking an onClick() method. Note that because UserInterface is an abstract class, no UserInterface objects can be constructed directly by new UserInterface( ). This makes sense because the UserInterface class is incomplete having no buttons to click and is designed to be extended.

The UserInterface implements an inner-class (one that is nested inside another class) of  ButtonHandler which wires each button to the event handler actionPerformed. The inner-class has access to all the UserInterface fields, instance and class methods. 

The event handled is a mouse click on a button, which invokes the actionPerformed() method which invokes the onClick()  method, passing the first character of the button label. The onClick() method must be over-ridden and functionality is added by classes inheriting the UserInterface class, an abstract (i.e. non-functional) version is defined here in order to satisfy the actionPerformed() method definition and require that inheriting classes define a functional onClick() method.

The purpose of each UserInterface method is:

UserInterface.java
 import java.awt.*;
 import java.awt.event.*;
 import java.applet.*;

 public abstract class UserInterface extends Applet
 {
          private class ButtonHandler implements ActionListener {
	 public void actionPerformed(ActionEvent e) {
		onClick(e.getActionCommand().charAt(0) );
	 }
          }

          private TextField        display;
          private ButtonHandler handler;
          private Panel             keypad;
         
          public UserInterface()
          {       
                 this.setLayout(new BorderLayout());
                 display = new TextField("0");
                 this.add("North", display);

                 keypad = new Panel();
                 keypad.setLayout(new GridLayout(4,5));
                 this.add("Center", keypad);
                 handler = new ButtonHandler();
          }

	public abstract void onClick( char c );

	public void addButton(String s) {
                 Button b = new Button(s);
                 keypad.add( b );
                 b.addActionListener( handler );
	}

           public void updateDisplay(String s) { display.setText(s); }

           public void init( ) { }
 }

Memory Calculator

m           12.34
1   2   3   +   -
4   5   6   *   /
7   8   9   0   =
CR RM SM MC

A memory calculator requires three buttons to store memory, recall memory, and clear memory. The buttons provide an interface of:

By inheriting the basic four function calculator of Calculator class the Memory class need add only:

MemoryCalculator class is then a Calculator class with the additional attributes and methods, specifically memory that can be stored, recalled or cleared using the SM, RM and MC buttons.

One important issue is how to access Calculator attributes (e.g. accumulator) without modifying the Calculator class? The answer is to use the get and set methods (e.g. getAccumulator( ) ) for each attribute provided specifically to expose attributes in a way that limits access (data encapsulation) and hides the details of the implementation (information hiding). This is not part of Java language but rather good programming practice.

A skeleton of the Memory Calculator:

MemoryCalculator.java
class MemoryCalculator extends Calculator
 { 
         public MemoryCalculator( )
         { }

	 public void onClick(char c)
         {       switch (c) {		 
			default  : super.onClick(c);
                 }
         }
 }

Scientific Calculator

A scientific calculator requires one or more buttons to provide an interface that:

By inheriting the basic four function calculator of Calculator class the Scientific class need add:

Assignment

  1. Do not modify UserInterface class.
  2. Complete the Calculator class to implement operations of -, *, /, and CR for clear. 
  3. Inherit the basic four function calculator of Calculator class to implement a Memory Calculator. You should not need to modify the Calculator.
  4. Inherit the MemoryCalculator class to implement a Scientific Memory calculator with at least one function of your choice. You should not need to modify the Calculator.
  5. Inherit any of the classes (UserInterface, Calculator, MemoryCalculator, ScientificCalculator) to produce a new application of your choice. You should not need to modify the Calculator.

Turn In

  1. Cover sheet with your name, date, and Homework 6.
  2. Calculator and HW6 listing.
  3. Screen shot of browser window after performing 1 / 3  = + 4 =.
  4. MemoryCalculator and modified HW6 listing.
  5. Screen shot of browser window after performing 4 + 5 = SM CR 6 + RM =.
  6. Scientific and modified HW6 listing.
  7. For some function FUN, screen shot of browser window after performing operations such as 4 + 5 = SM CR 6 + RM = FUN.
  8. Your new class and HW6 listing.
  9. Screen shot showing execution of your class.

Getting Started

  1. Copy all the sections to the named files:
  2. Set path to compiler
  3. Compile HW6
  4. Execute the applet

Testing

Browsers can execute applets but, because most browsers do not reload applets, are not easily used for repetitively testing an applet. An applet testing platform is provided with the Java SDK from SUN. To use it at IUS with the HW6.htm file enter:

appletviewer HW6.htm

HW6.htm file

<APPLET code="HW6.class" width=100 height=100>
</APPLET>

Document last modified: