// Demo for usage of standard methods in an applet.
// Runs in its own thread, continuously drawing a Pac-man figure
// in two alternating colors.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;

public class ThreadApplet extends Applet implements Runnable 
  {
    private Thread appletThread = null;
    private boolean stopped = false;
    private int mouthGap = 0;

    public void init() 
      {
        // Set the foreground color
        setForeground(Color.green);
        // Alternate mouse clicks will stop or restart the painting.
        addMouseListener(new MouseAdapter() 
          {
            public void mouseClicked(MouseEvent e) 
              { toggleAnimation(); }
          });
      }

    public void start() 
      {
        // Create and start a thread if none present.
        if (appletThread == null) 
          {
            appletThread = new Thread(this);
            appletThread.start();
          }
      }

    public void stop() 
      {
        appletThread = null;
      }

    public void run() 
      {
        Thread thisThread = Thread.currentThread();
        while (thisThread == appletThread) 
          {
            // Change foreground color while running.
            // Painting color will change accordingly.
            if(getForeground().equals(Color.green))
                setForeground(Color.blue);
            else
                setForeground(Color.green);
            // Update mouth gap
            mouthGap = (mouthGap+5) % 60;
            // Update the screen
            repaint();
            showStatus("Click to stop.");
            // Take a break between painting
            try {
                  Thread.sleep(100);
                  // If drawing is stopped, then wait.
                  synchronized(this) 
                    {
                      while (stopped)
                        {
                          showStatus("Click to restart.");
                          wait();
                        }
                    }
                } 
            catch (InterruptedException e) {}
          }
      }

    public void paint(Graphics gfx) 
      {
        // Draw a "Pac-man" in the current color
        int angle = Math.abs(mouthGap-30) + 5;  // Set mouth angle
        gfx.fillArc (50, 50, 50, 50, angle, 360 - angle*2);
      }

    private synchronized void toggleAnimation() 
      {
        // Check if the thread is present.
        if (appletThread != null && appletThread.isAlive())
          {
            // Toggle between stopping and resuming the painting
            stopped = !stopped;
            // If drawing should restart, then notify.
            if (!stopped)
                notify();
          } 
        else 
          { // No thread. Create one and start it. 
            stopped = false;
            start();
          }
      }
  }
