Programming and Problem Solving with Java

(やまだぃちぅ) #1

CASE STUDY^405


the data entry field, the button, and the output label. We want each instance of the
class to have its own copy of the fields, so they should be instance fields (nonstatic).
None of the fields is used outside of the class, so they all involve package-level access.
The button needs an event handler, so we also declare an ActionHandlerclass, nested
within the class. Of course, we need an instance field to hold the total, and it should be
a doublevariable that is initialized to 0.0. Here are the class declarations that we’ve
identified so far:


We want the user interface elements to be incorporated in a unit that can be added
to a content pane. This “unit” sounds a bit like a pane, but we can’t put a pane inside a
pane. Browsing through your Java library reference, you discover the class JPanel, which
is a Containerobject that can have a layout manager and hold user interface
components, just like a content pane. It can also be added to a content pane so that its
contents appear within the pane. This is a perfect example of the building-block
approach! We can add these components to a JPanelthat is an instance field in our
Stationobject.
The job of the constructor is then to initialize all of these fields.


To get the panel from the object, we use a value-returning instance method that re-
turns a reference to panel.


Lastly, we have to design an ActionListenerimplementation within our Stationclass.
We want the event listener to be unique to each instance of Station. That way, the but-
ton in each Stationobject has an event handler that can directly access the station’s


Instance method getPanel, has no parameters and returns a JPanel reference
returnpanel

Constructor Station, takes one parameter, name, of class String
Create a JPanel object, panel
Set the layout manager for the panel to FlowLayout
Create the text field, amountField, leaving space for 10 digits, and
initializing it to "0.0"
Create a button called enter
Create an event handler for the button
Register the handler with the button
Create a label called outputLabel and initialize it to "Total Rainfall: 0.0"
Add a label to the panel with "Station " + name + ":"
Add amountField to the panel
Add enter button to the panel
Add outputLabel to the panel

A text field for data entry
A button to signal when data is ready
A label to hold output
An ActionHandler to handle the button events
Total, a double variable
Free download pdf