Computer Science Example
A Java applet that coverts Fahrenheit temperatures to Celsius temperatures.

To run this applet, click on TempConvert.htm.

import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
import java.text.*;

/*An applet that creates a button, 2 labels, 2 text fields and a panel.  It adds these to the applet along with an action listener for the button. */
public class TempConversion extends Applet
{
     private Button calculate;
     private Label lblFahrenheit, lblCelsius;
     private TextField txtFahrenheit, txtCelsius;
     private Panel panel;

     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.  When clicked, it converts the number in the txtFahrenheit box into a celsius value and displays it in the txtCelsius box. */
     class CalculateListener implements ActionListener
     {
          public void actionPerformed (ActionEvent event)
          {
               double fahrenheit, celsius;
                fahrenheit = Double.parseDouble (txtFahrenheit.getText ());
                celsius = (fahrenheit - 32) * 5 / 9;
                txtCelsius.setText ("" + NumberFormat.getNumberInstance ().format (celsius));
          } // method actionPerformed
     } // class CalculateListener
} // class TempConversion