import java.applet.*;
import java.awt.*;
import java.awt.event.*;

/**
 * A simple applet to demonstrate the Event model and LayoutManager usage
 * @author Janne Kalliola <Janne.Kalliola@hut.fi>
 */

public class Example extends Applet implements ActionListener {
  private Button inc = new Button("Increase");
  private Button clear = new Button("Clear");
  private ExampleCanvas canvas;

  /**
   * Initializes the applet. Creates LayoutManagers and add components to
   * them.
   */

  public void init() {

    /* To make the applet look good, we'll use a simple panel to layout
     * the buttons in a row. The panel works just like the applet, in fact
     * applet is an extended panel.
     *
     * First we create a new panel and set its LayoutManager as a new
     * GridLayout with two horizontal slots and unknown number of
     * vertical slots. Then we add the buttons to this panel. They will
     * take their own places with the help of the LayoutManager 
     */

    Panel p = new Panel();
    p.setLayout(new GridLayout(0, 2));
    p.add(inc);
    p.add(clear);

    /* Let's create the canvas to hold the bar. We have extended a new
     * canvas class from class Canvas, called ExampleCanvas. It has some
     * nifty properties, see its code.
     */

    canvas = new ExampleCanvas(5);

    /* In the applet we'll be using BorderLayout which is rather nice when
     * we want to stretch something from corner to corner. The Center
     * of the BorderLayout will be stretched both horizontally and
     * vertically, the South only horizontally.
     */

    setLayout(new BorderLayout());
    add("Center", canvas);
    add("South", p);

    /* Because we want this applet to react when the user clicks the
     * buttons, we'll add an ActionListener to them. As this applet
     * happens to implement ActionListener interface, we can use it.
     */

    inc.addActionListener(this);
    clear.addActionListener(this);
  }

  /**
   * Method to implement the ActionListener interface. This method is
   * called every time user clicks one of the buttons.
   * @param event the event occurred
   */

  public void actionPerformed(ActionEvent event) {

    /* We have two buttons and only one ActionListener. No problems, we'll
     * just check the event as it knows the buttons where it was generated.
     * After we know the button, we launch simple methods from the
     * ExampleCanvas, which will do the hard work.
     */

    if (event.getActionCommand().equals("Increase")) {
      canvas.incrementValue();
    } else if (event.getActionCommand().equals("Clear")) {
      canvas.clearValue();
    }
  }
}
