import java.io.*;
import java.text.*;
import java.awt.event.*;
import java.awt.*;
/* The TempConvert class is a frame. It displays two labels, two
text boxes and a button. When the button is clicked, the number in
the first box is converted from Fahrenheit to Celsius. */
class TempConvert extends Frame
{
private Button convert;
private Label fahrenheitLabel, celsiusLabel;
private TextField fahrenheit, celsius;
private Panel panel;
/* The constructor first adds a listener to
the window so that clicking the closing icon will close the window.
It then creates a panel and adds the labels, text boxes and button to the
panel. A listener is added to the button and the panel is added to
the frame. */
TempConvert ()
{
super ("Temperature
Conversion");
setSize (200,
200);
// Add a window
closer to the frame.
addWindowListener
(new WindowAdapter() {public void windowClosing(WindowEvent e) {System.exit(0);}});
// Get a new
panel and set its background color.
panel = new
Panel ();
panel.setBackground
(Color.cyan);
// Get the labels
and text boxes and add them to the panel.
fahrenheitLabel
= new Label ("Fahrenheit");
fahrenheit =
new TextField (10);
panel.add (fahrenheitLabel);
panel.add (fahrenheit);
celsiusLabel
= new Label ("Celsius");
celsius = new
TextField (10);
panel.add (celsiusLabel);
panel.add (celsius);
// Get a new
button and add a listener to it.
convert = new
Button ("Convert");
convert.addActionListener
(new ConversionListener ());
panel.add (convert);
// Add the panel
to the frame.
add (panel);
} // constructor
// Inner class to listen for the convert button.
class ConversionListener implements ActionListener
{
public void
actionPerformed (ActionEvent event)
{
try
{
double f, c;
f = Double.parseDouble (fahrenheit.getText ());
c = (f - 32) * 5 / 9;
celsius.setText ("" + decimals (c));
} catch (NumberFormatException e) {celsius.setText ("Error");}
} // method
actionPerformed
} // class ConversionListener
// Formats a double for string output with
two decimal places.
public static String decimals (double num)
{
DecimalFormat
decFor = new DecimalFormat ();
decFor.setMaximumFractionDigits
(2);
decFor.setMinimumFractionDigits
(2);
return decFor.format
(num);
} // decimals
// The main method gets a new frame and shows
it.
public static void main (String [] args)
{
TempConvert
frame = new TempConvert ();
frame.show ();
}
} // class TempConversion