Java Reference
In-Depth Information
in the rectangle program earlier in this chapter, we can create the window by making
the application extend the
class
JFrame
. To get access to the container, we will use
a reference variable of the
Container
type. To create labels, we use objects of type
JLabel
; to create text fields, we use objects of type
JTextField
. Suppose that we
have the following declarations:
JLabel celsiusLabel;
//label Celsius
JLabel fahrenheitLabel;
//label Fahrenheit
JTextField celsiusTF;
//text field Celsius
JTextField fahrenheitTF;
//text field Fahrenheit
When the user enters the temperature in the text field
celsiusTF
and presses the
Enter
key, we want the program to show the equivalent temperature in the text field
fahrenheitTF
and vice versa.
Recall that when you click a
JButton
, it generates an action event. Moreover, the
action event is handled by the method
actionPerformed
of the
interface
ActionListener
. Similarly, when you press the
Enter
key in a text field, it
generates an action event. Therefore, we can register an action event listener with
the text fields
celsiusTF
and
fahrenheitTF
to take the appropriate action.
Based on this analysis and the GUI shown in Figure 6-9, you can design an event-
driven algorithm as follows:
1. Have a listener in each text field.
2. Register an event handler with each text field.
3. Let each event handler registered with a text field do the following:
a. Get the data from the text field once the user presses
Enter
.
b. Apply the corresponding formula to perform the conversion.
c. Set the value of the other text field.
This process of adding an event listener and then registering the event listener to a
text field is similar to the process we used to register an event listener to a
JButton
earlier in the chapter. (This process will be described later in this programming
example.)
The input to the program is either the temperature in Celsius or the temperature in
Fahrenheit. If the input is a value for Celsius, then the program calculates the
equivalent temperature in Fahrenheit. Similarly, if the input is a value for Fahrenheit,
then the program calculates the equivalent temperature in Celsius. Therefore, the
program needs the following variables:
VARIABLES,
OBJECTS,
AND NAMED
CONSTANTS
double
celsius;
//variable to hold Celsius
double
fahrenheit;
//variable to hold Fahrenheit
Search WWH ::
Custom Search