Java Reference
In-Depth Information
public
TempConversion()
{
setTitle("Temperature Conversion");
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(
true
);
}
public static void
main(String[] args)
{
TempConversion tempConv =
new
TempConversion();
}
}
Now you need to access the container content pane to place the GUI components
and set the required layout of the pane. Therefore, as before, you need the following
statements:
Container c = getContentPane();
//get the container
c.setLayout(
new
GridLayout(1, 4));
//create a new layout
c.add(celsiusLabel);
//add the label celsiusLabel
//to the container
c.add(celsiusTF);
//add the text field celsiusTF
//to the container
c.add(fahrenheitLabel);
//add the label fahrenheitLabel
//to the container
c.add(fahrenheitTF);
//add the text field fahrenheitTF
//to the container
You want your program to respond to the events generated by
JTextFields
.
Just as when you click a
JButton
an action event is generated, when you press
Enter
in a
JTextField
, it generates an action event. Therefore, to register
event listeners with
JTextFields
, we use the four steps outlined in the section
Handling an Event earlier in this chapter: (1) create a class that implements the
interface
ActionListener
; (2) provide the definition of the method
actionPerformed
within the class that you created in Step 1; (3) create and
instantiate an object of the class created in Step 1; and (4) register the event
handler created in Step 3 with the object that generates an action event using the
method
addActionListener
.
Next, we create and register an action listener with the
JTextField celsiusTF
.
First we create the
class
CelsHandler
, implementing the
interface
ActionListener
. Then, we provide the definition of the method
actionPerformed
of the
class
CelsHandler
. When the user enters the tempera-
ture in the
JTextField celsiusTF
and presses
Enter
, the program needs to
calculate
and
display
the
equivalent
temperature
in
the
JTextField
Search WWH ::
Custom Search