Fahrenheit to Celsius Converter - 1.1 Events

© Copyright University of New Haven 1998

Home Page

The following program uses 1.1 event handling, and therefore may not run on some browsers. It is designed to run either as an applet, or stand-alone.

import java.awt.*;
import java.awt.event.*;

public class FC extends java.applet.Applet
{
        public void start()                  { new F2C11(this); }
        public static void main(String s[])  { new F2C11(null); }
}

class F2C11 extends Frame
{
        Container invokedby;

        public F2C11(Container c)
        {
                super("Temperature Converter");

                invokedby= c;
                setLayout(new FlowLayout());
                Label result=
                    new Label("                                                ");
                add(new Label("Enter a Fahrenheit temperature: "));
                Panel wkarea= new Panel();
                wkarea.add(new Inputfield(result));
                wkarea.add(new Quitbutton(this));
                add(wkarea);
                add(result);
                addWindowListener(new Exit(this));
                resize(500, 100);
                show();
        }
}

class Exit extends WindowAdapter implements ActionListener
{
        F2C11 creator;

        Exit(F2C11 f)  { creator= f; }

        void leave()
        {
                if  (creator.invokedby instanceof FC)  creator.dispose();
                else                         System.exit(0);
        }

        public void actionPerformed(ActionEvent e) { leave(); }
        public void windowClosing(WindowEvent e)   { leave(); }
}

class Inputfield extends TextField implements TextListener
//class Inputfield extends TextField implements ActionListener
{
        Label result;

        Inputfield(Label l)
        {
                super(10);
                result= l;
                addTextListener(this);
//              addActionListener(this);
        }

        public void textValueChanged(TextEvent e)
//      public void actionPerformed(ActionEvent e)
        {
                float t= 0;

                result.setText("");
                try { t= new Float(getText()).floatValue(); }
                catch(Exception ex) { return; }
                t= (t-32)*5/9;
                result.setText(t + " degrees Celsius");
        }
}

class Quitbutton extends Button
{
        Quitbutton(F2C11 f) { super("QUIT");  addActionListener(new Exit(f)); }
}
Home Page