CASE STUDY^417
The algorithm for handling the Clear button is even simpler; all we have to do is set
the register to zero as well as the variable that contains the same value. We should also
clear the input field. These actions are performed in the actionPerformedmethod of the
class ClearHandler.
As in our previous applications, we must decide where each object should be
declared. Because we are writing this application as just a single class that won’t be in-
stantiated by user code, we can make all of the members static and declare them at the
class level.
The coding of the algorithm into Java is now easy. Here is the result:
//
// This application implements a simple on-screen calculator
//
importjava.awt.; // awt interface classes
importjava.awt.event.; // awt event classes
importjavax.swing.*; // User interface classes
public classCalculator
{
staticJTextField inputField; // Data entry field
staticJLabel register; // Result shown on screen
static doubleresult; // Keeps current value
staticJFrame calcFrame; // Declare a frame
staticContainer calcPane; // Container to hold
// content pane of frame
staticNumericHandler operation; // Declare numeric listener
staticClearHandler clearOperation; // Declare clear listener
staticJLabel resultLabel; // Indicate output area
staticJLabel entryLabel; // Label for input field
staticJButton add; // Add button
Handle Clear Button Event Level 1
Set result to zero
Display result in register
Clear inputField
Handle Numeric Button Events Level 1
Set secondOperand to numerical value (double) of entry string
Set whichButton to name of event source
ifwhichButton is "+"
Set result to result + secondOperand
else
Set result to result – secondOperand
Display result in register
Clear inputField