The Fahrenheit Applet:
Code:
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
//-------------------------------------------------------------------
//
// Class Fahrenheit is an applet that accepts temperature in
// fahrenheit and converts it to celcius.
//
//-------------------------------------------------------------------
public class Fahrenheit extends Applet
{
private Label title = new Label ("Fahrenheit to Celcius Converter");
private Label question = new Label ("Enter Fahrenheit:");
private Label answer = new Label ("Temperature in Celcius:");
private TextField fahrenheit = new TextField (5);
private Label celcius = new Label ("N/A");
private TextArea log = new TextArea (5, 20);
private Fahrenheit_Listener listener = new Fahrenheit_Listener (this);
//===========================================================
// Sets up the applet with its various components.
//===========================================================
public void init()
{
fahrenheit.addActionListener (listener);
log.setEditable (false);
add (title);
add (question);
add (fahrenheit);
add (answer);
add (celcius);
add (log);
resize (200,200);
}
//===========================================================
// Performs the conversion and displays it in the label
// and log.
//===========================================================
public void convert()
{
int fahrenheit_temperature, celcius_temperature;
String text = fahrenheit.getText();
fahrenheit_temperature = Integer.parseInt (text);
celcius_temperature = (fahrenheit_temperature-32)*5/9;
celcius.setText (Integer.toString (celcius_temperature));
log.append (text + " converts to " + celcius.getText() + "\n");
}
} // class Fahrenheit
class Fahrenheit_Listener implements ActionListener
{
private Fahrenheit applet;
//===========================================================
// Sets up the listenter object.
//===========================================================
public Fahrenheit_Listener (Fahrenheit listening_applet)
{
applet = listening_applet;
}
//===========================================================
// Calls the conversion method when an action event (the
// user pressing enter) occurs.
//===========================================================
public void actionPerformed(ActionEvent action)
{
applet.convert();
}
}