Programming and Problem Solving with Java

(やまだぃちぅ) #1

CASE STUDY


416


We still have one more step in mainto flesh out.

Registering an event listener for a button involves three steps: declare a variable of
the listener class, instantiate a listener object, and add the listener object to the button.
The listener for the numeric operations is, of course,NumericHandler.

For the clear operation, we just substitute ClearHandler.

We have now completed the responsibility algorithms for the application class
Calculator. The remaining classes handle the buttons. First, we design the listener for
the numeric buttons. We have said that the listener class is called NumericHandler. What
should the actionPerformedmethod do when the user clicks the add or subtract button?
It should get the value to be used in the calculation from the input field and convert it
to a real number. If the user enters a string that does not represent a legitimate real
number, a NumberFormatExceptionmay be thrown. In Chapter 9, we show you how to han-
dle this exception; here, we assume correct input.
Next, we determine which operation should be applied to the number, addition or
subtraction. Wait a minute: Addition and subtraction are binary operations! We have
one value; where is the other one? Actually, the value just input is the second operand.
The first operand is the value in the register. Rather than extract it from the window
each time, we should keep a copy in numeric form. (We must be sure to set that value
to zero originally.) Back to the question of determining which button was clicked: We
use the parameter in the actionPerformedmethod to tell us.

Register the Event Listener for the Clear Button
Declare a ClearHandler, clearOperation
Instantiate a ClearHandler for clearOperation
add clearOperation as listener for clear button

Register the Event Listener for the Arithmetic Buttons
Declare a NumericHandler, operation
Instantiate a NumericHandler for operation
add operation as listener for arithmetic buttons

Register Listeners with Buttons
Register the event listener for the arithmetic buttons
Register the event listener for the clear button

Add Each Interface Object to the Pane
Add resultLabel to calcPane
Add register to calcPane
Add entryLabel to calcPane
Add inputField to calcPane
Add add to calcPane
Add subtract to calcPane
Add clear to calcPane
Free download pdf