CSC 8310 -- Threads

Dr. David Matuszek,   dave@acm.org
Fall 1998, Villanova University

This applet draws random rectangles in random colors. There is a single button to both start drawing and stop drawing; the button label changes according to which of these it will do next.

Since drawing the rectangles is done in an infinite loop, there would be no opportunity for the Stop button to have any effect. To solve this problem, a separate Thread is created to do the drawing; this is the usual way to do animation in Java.

Note: This is a picture of the applet, not the applet itself. The applet itself is not included because Java 1.1 is not supported on Netscape browsers.

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

// <applet code="ThreadExample.class" height=200 width=200> </applet>

public class ThreadExample extends Applet implements Runnable
{
  Button goButton = new Button ("Start/Stop");
  Thread paintThread;
  boolean running = false;
  
  public void init ()
  {
    add (goButton);
    goButton.addActionListener (new ActionListener () {
      public void actionPerformed (ActionEvent event)
	{
          if (running) stop ();
          else start ();
        }
    });
  }

  public void start ()
  {
    paintThread = new Thread (this);
    paintThread.start ();
    goButton.setLabel ("Stop");
    running = true;
  }
  
  public void stop ()
  {
    paintThread.stop ();
    running = false;
    goButton.setLabel ("Start");
  }
  
  public void run ()
  {
    while (true)
      {
        repaint ();
        try { Thread.sleep (100); }
        catch (InterruptedException e) { };
      }
  }
  
  // The default update() clears the screen between calls to
  //   paint(), so only the most recent rectangle is visible.
  //   I don't want the screen cleared, so I override update().
  public void update (Graphics g) { paint (g); }

  public void paint (Graphics g)
  {
    int red, green, blue, left, top, width, height;
    {
      red    = (int) (Math.random () * 256);
      green  = (int) (Math.random () * 256);
      blue   = (int) (Math.random () * 256);
      top    = (int) (Math.random () * 100);
      left   = (int) (Math.random () * 100);
      width  = (int) (Math.random () * 100);
      height = (int) (Math.random () * 100);
      g.setColor (new Color (red, green, blue));
      g.fillRect (left, top, width, height);
    }
  }
}