Java Reference
In-Depth Information
}
}
class
ConverterFrame
extends
JFrame
{
public
ConverterFrame ()
{
setDefaultCloseOperation(JFrame.DISPOSEON CLOSE) ;
setLayout(
new
BorderLayout () ) ;
//not required
JPanel cPanel =
new
JPanel () ;
JPanel fPanel =
new
JPanel () ;
JPanel buttonPanel =
new
JPanel () ;
final
JTextField cField =
new
JTextField(20) ;
final
JTextField fField =
new
JTextField(20) ;
cPanel .add(
new
JLabel(
"Celsius: "
));
cPanel .add( cField) ;
fPanel .add(
new
JLabel(
"Fahrenheit: "
));
fPanel .add( fField) ;
JButton convertButton =
new
JButton(
"CONVERT"
);
buttonPanel .add(convertButton) ;
add(cPanel , BorderLayout .NORTH) ;
add( fPanel , BorderLayout .CENTER) ;
add(buttonPanel , BorderLayout .SOUTH) ;
convertButton . addActionListener(
new
ActionListener ()
{
public void
actionPerformed(ActionEvent e)
{
if
(cField.getText().trim().equals(
""
) && fField . getText () . trim
() . equals(
""
))
{
return
;
if
(cField.getText().trim().equals(
""
))
{
String result = fField.getText() .trim() ;
double
number = Double . parseDouble ( r e su l t ) ;
number = (number
−
32)
∗
(5/9.0) ;
cField . setText(
""
+ number) ;
if
( fField . getText () . trim() . equals (
""
))
{
String result = cField.getText() .trim() ;
double
number = Double . parseDouble ( r e su l t ) ;
number = number
∗
(9 / 5.0) + 32;
fField .setText(
""
+ number) ;
}
}
}
);
pack() ;
}
}
The code creates three panels: in the north, center, and south. In each panel, several
components are added. Since the default layout for a panel is the flow layout, the components
are added in the panel using the flow layout (i.e., they are placed from left to right inside the
panel). The
actionPerformed
method is associated with the
CONVERT
button. The method
first checks if both the Celsius and Fahrenheit text fields are empty. If this is the case, then
there is nothing to do. If only one of them is empty, then its value is calculated based on
the value of the other field. The
parseDouble
static method of the
Double
classisusedto
convert a
String
to a
double
.Thereisalsoa
parseInt
static method in the class
Integer
that converts a string to an integer. If the conversion fails, that is, the input is not a number,
then an exception is raised. The
setText
method is used to set the new value of the text