Programming and Problem Solving with Java

(やまだぃちぅ) #1

CASE STUDY^403


Scenarios:What happens when an observer calls in with a rainfall amount? The user in-
terface CRC card is raised, and it must collaborate with a station. Each station is an in-
stance of the Station class, and we want to enter the rainfall amount for the particular
station. We then click a button and see the new total. Thus a station needs to have a
button, a data entry field, and a label for output. It also needs to label the field and the
output with descriptions.
After a value has been entered, the user clicks the button; the station should then
add the value to the total and the new total should be displayed. The data entry field
should also be reset to 0.0 to indicate that the field is ready for more input. This default
value has the advantage that if you accidentally click its button without entering a new
value, the total isn’t affected. When designing an object that is also a user interface
component, it is a good idea to draw it out by hand to make sure that it is complete and
understandable.


We initially state that Stationcollaborates with three library classes: JLabel,JButton,
and JTextField. Of course, we need an event handler for the button, so it also needs to
collaborate with an ActionHandler(a class we will write that implements the
ActionListenerinterface).
Until now, we’ve used mainto set up all of the elements in a user interface. But much
of what a station does is related to its part of the user interface. Let’s make a Stationob-
ject be responsible for creating its own portion of the interface and returning it for main
to add as a unit to the frame.
What are the responsibilities of a Station object?


1.Create each piece of the user interface when it is instantiated.
2.Return the station’s portion of the user interface.
3.Handle button clicks by reading a value, updating the total, and resetting the
data entry field.

The first responsibility has to be a constructor, as it takes place during instantiation.
Returning the user interface components is the task of an instance method. Handling
button events is the job of an event handler. So, it sounds like our Station object needs
three methods. Here is the CRC card as it now stands:


Station xxxxxxxxxxx 0.0 Enter Total Rainfall: 123.05

Free download pdf