Fahrenheit to Celsius Converter - 1.0 Events

© Copyright University of New Haven 1998

Home Page

The following program uses 1.0 event handling to maximize portability. It is designed to run either as an applet, or stand-alone.

import java.awt.*;

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

class F2C10 extends Frame
{
        Container invokedby;

        public F2C10(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);
                resize(500, 100);
                show();
        }

        public boolean handleEvent(Event e)
        {
                if  (e.id == e.WINDOW_DESTROY)
                     if  (invokedby instanceof FC)  dispose();
                     else                           System.exit(0);
                return false;
        }
}

class Inputfield extends TextField
{
        Label    result;

        Inputfield(Label l)
        {
                super(10);
                result= l;
        }

        public boolean handleEvent(Event e)
        {
//              if  (e.id == e.ACTION_EVENT)
                if  (e.id == e.KEY_RELEASE)  
                {
                        float t= 0;

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

class Quitbutton extends Button
{
        F2C10 creator;

        Quitbutton(F2C10 f) { super("QUIT");   creator= f; }

        public boolean handleEvent(Event e)
        {
                if  (e.id == e.ACTION_EVENT)
                     if  (creator.invokedby instanceof FC)  creator.dispose();
                     else                                   System.exit(0);
                return false;
        }
}
Home Page