/* DumbCalc.

This is an example which illustrates two User Interface components:
TextFields and Buttons. Clicking on the buttons affects the
entry in the TextField, as does typing in the TextField.

Specifically: you can enter a base 10 number in the TextField
using the calculator buttons (0 and 1) or by typing.
The = button computes the residue mod 2.
The C button clears the TextField to 0.

If you type in anything other than an integer, the screen is reset to
0 when you press =. Weird things happen when you enter more than 
10 digits: watch the diagnostic on stdout.
*/

import java.lang.*;
import java.awt.*;
import java.applet.*;

public class DumbCalc extends Applet {

  TextField screen;

     /* need to declare this, otherwise it's local to init */

  public void init() {

    screen = new TextField("0",10);
    add(screen);
        /* need a name to refer to this TextField */
    add(new Button("0")); 
    add(new Button("1")); 
    add(new Button("=")); 
    add(new Button("C")); 
        /* don't need a name to refer to these Buttons */
    show();
        /* Layout manager is the default: FlowLayout.
           "show" puts the components on the screen. */

  }

  int getValue(TextField s) {
	/* A function ("Method") which converts the string in 
           the TextField s
           to an integer, or 0 if not a number */
    int f;
    try {
      f = java.lang.Integer.parseInt(s.getText());

    } catch (java.lang.NumberFormatException e) {
      f = 0;
      }
    return f;
  }


  public boolean handleEvent(Event e) {

        /* What to do when a user types or clicks the mouse */

    if ((e.id == Event.ACTION_EVENT) && (e.target instanceof Button)) {
        String b = ((Button)e.target).getLabel();
        if ((b == "0") || (b == "1")) {

  	    /* When the user clicks the 0 or 1 button... */

	  screen.setText(screen.getText() + ((Button)e.target).getLabel());

	    /* the digit is appended to the string on the screen */
	}
        else if (b == "=") {
          screen.setText(java.lang.Integer.toString(getValue(screen)%2));
            /* The integer (base 10) in the screen is reduced mod 2 */
	}
	else if (b == "C") {
          screen.setText("0");
            /* clears the screen */
        }

    else if (e.target instanceof TextField) {
      screen.setText(screen.getText());
           /* Can also type into the TextField */
    }

      System.out.println(getValue(screen));
        /* Diagnostic which prints to stdout (e.g., the window
           from which you invoked appletviewer) */
      return true;
    }
    return false;
  }
}
