// To run this click on TempConvert.html
import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
import java.text.*;
// A Java applet that coverts Fahrenheit temperatures to Celsius temperatures.
public class TempConversion extends Applet
{
private Label lblFahrenheit, lblCelsius;
private TextField txtFahrenheit, txtCelsius;
private Button Calculate;
private Panel panel;
// Method that gets the components and puts
them on the applet.
public void init ()
{
setBackground
(Color.cyan);
panel = new
Panel ();
panel.setLayout
(new GridLayout (5, 1, 12, 12));
lblFahrenheit
= new Label ("Fahrenheit");
txtFahrenheit
= new TextField (10);
lblCelsius =
new Label ("Celsius");
txtCelsius =
new TextField (10);
Calculate =
new Button ("Calculate");
Calculate.addActionListener
(new CalculateListener ());
panel.add (lblFahrenheit);
panel.add (txtFahrenheit);
panel.add (lblCelsius);
panel.add (txtCelsius);
panel.add (Calculate);
add (panel);
} // method init
// Inner class to listen for the Calculate
button.
class CalculateListener implements ActionListener
{
public void
actionPerformed (ActionEvent event)
{
double fahrenheit, celsius;
fahrenheit = AppletIO.getDouble (txtFahrenheit);
celsius = (fahrenheit - 32) * 5 / 9;
txtCelsius.setText ("" + AppletIO.decimals (celsius));
} // method
actionPerformed
} // class CalculateListener
} // class TempConversion
// A class that handles IO for an applet.
class AppletIO
{
// Gets a double from the TextField and returns
it to the calling method.
public static double getDouble (TextField
box)
{
double number;
try
{
number = Double.valueOf (box.getText ()).doubleValue ();
} catch (NumberFormatException
e) { number = 0;}
return number;
} // method getDouble
// Formats a double for string output with
two decimal places.
public static String decimals (double number)
{
DecimalFormat
decFor = new DecimalFormat ();
decFor.setMaximumFractionDigits
(2);
decFor.setMinimumFractionDigits
(2);
return decFor.format
(number);
} // method decimals
// Gets an integer from the TextField and returns
it to the calling method.
public static int getInteger (TextField box)
{
int number;
try
{
number = Integer.parseInt (box.getText());
} catch (NumberFormatException
e) { number = 0;}
return number;
} // method getInteger
} // class AppletIO
<HTML>
<HEAD>
<TITLE>Temperature Conversion</TITLE>
</HEAD>
<BODY>
<H1>Temperature Conversion</H1>
<APPLET CODE="TempConversion.class"
WIDTH=300 HEIGHT=300></APPLET>
</BODY>
</HTML>