Programming and Problem Solving with Java

(やまだぃちぅ) #1

CASE STUDY


406


fields. So, we must make the event handler be an instance class (not static). What does
the event handler do when the user clicks the button? It gets the string from the input
field, converts it to a doublevalue (using parseDouble), adds it to the total, updates the
output label, and resets the input field to 0.0.

We are now ready to code the Stationclass.

//****************************************************************************
// This package provides a class for rainfall reporting stations. Each
// station is represented by a separate panel that contains its own
// user interface elements.
//****************************************************************************
package station;
importjava.awt.*; // Layout manager
importjava.awt.event.*; // Event-handling classes
importjavax.swing.*; // User interface classes
public class Station
{
JButton enter; // Enter data button
JTextField amountField; // Data entry field
JLabel outputLabel; // Result display label
JPanel panel; // Panel for user interface
ActionHandler action; // Event handler
doubletotal = 0.0; // Total rainfall

publicStation (String name) // Station constructor
{
// Set up panel to hold user interface elements
panel = newJPanel(); // Get a panel
panel.setLayout(newFlowLayout()); // Set layout for the panel
// Create user interface elements
amountField = newJTextField("0.0", 10 ); // Field for data entry
enter = newJButton("Enter"); // Enter button
action = newActionHandler(); // Create an event handler
enter.addActionListener(action); // Register handler with button
outputLabel = newJLabel("Total Rainfall: " // Label for output
+ total);
// Add user interface elements to panel
panel.add(newJLabel("Station "+ name + ":"));

Private Class ActionHandler implements ActionListener
Public void method actionPerformed takes one parameter, event, of class ActionEvent
Declare a local variable, value, of type double, to hold the input value
Assign value the result of applying parseDouble to the value from
amountField.getText
Set total to total plus value
Use setText to update outputLabel with "Total Rainfall: " + total
Use setText to reset amountField to "0.0"
Free download pdf