Easy to Learn Java: Programming Articles, Examples and Tips

Start with Java in a few days with Java Lessons or Lectures

Home

Code Examples

Java Tools

More Java Tools!

Java Forum

All Java Tips

Books

Submit News
Search the site here...
Search...
 

The Bounce class; create and start Sprites, using Threads Java code example - Click here to copy ->>>

   Can't find what you're looking for? Try our search:

Really working examples categorized by API, package, class. You can compile and run our examples right away! Not from source code for Java projects - only working examples! Copy, compile and run!
------------------

Code:

<TITLE>A Bounce of a Demo</TITLE>
<BODY BGCOLOR=Yellow>
<H1>A Bounce of a Demo</H1>
<APPLET CODE="Bounce" WIDTH=300 HEIGHT=200>
</APPLET>
</BODY>

/*
 * Copyright (c) Ian F. Darwin, http://www.darwinsys.com/, 1996-2002.
 * All rights reserved. Software written by Ian F. Darwin and others.
 * $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
*/


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

/** This is the Bounce class; create and start Sprites, using Threads. */
public class Bounce extends Applet implements ActionListener {
  /** The main Panel */
  protected Panel p;
  /** The image, shared by all the Sprite objects */
  protected Image img;
  /** A Vector of Sprite objects. */
  protected Vector v;

    public void init() {
    Button b = new Button("Start");
    b.addActionListener(this);
    setLayout(new BorderLayout());
    add(b, BorderLayout.NORTH);
    add(p = new Panel(), BorderLayout.CENTER);
    p.setLayout(null);
    String imgName = getParameter("imagefile");
    if (imgName == nullimgName = "duke.gif";
    img = getImage(getCodeBase(), imgName);
    MediaTracker mt = new MediaTracker(this);
    mt.addImage(img, 0);
    try {
      mt.waitForID(0);
    catch(InterruptedException e) {
      throw new IllegalArgumentException(
        "InterruptedException while loading image " + imgName);
    }
    if (mt.isErrorID(0)) {
      throw new IllegalArgumentException(
        "Couldn't load image " + imgName);
    }
    v = new Vector();
    }

    public void actionPerformed(ActionEvent e) {
    System.out.println("Creat-ing another one!");
    Sprite s = new Sprite(this, img);
    s.start();
    p.add(s);
    v.addElement(s);
    }

    public void stop() {
    for (int i=0; i<v.size(); i++) {
      ((Sprite)(v.get(i))).stop();
    }
    v.clear();
    }
}
/**
* Java Code from Java Cookbook, Second Edition
* By Ian F. Darwin
* Second Edition June 2004
* Series: Cookbooks
* ISBN: 0-596-00701-9
* Details: http://www.oreilly.com/catalog/javacook2/index.html
* Copyright (c) Ian F. Darwin, http://www.darwinsys.com/, 1996-2002.
* All rights reserved. Software written by Ian F. Darwin and others.
* $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
*/
/*
 * Copyright (c) Ian F. Darwin, http://www.darwinsys.com/, 1996-2002.
 * All rights reserved. Software written by Ian F. Darwin and others.
 * $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
*/

import java.awt.*;

/** A Sprite is one Image that moves around the screen on its own */
public class Sprite extends Component implements Runnable {
  protected static int spriteNumber = 0;
  protected Thread t;
  protected int x, y;
  protected Component parent;
  protected Image img;
  protected boolean done = false;
  /** The time in mSec to pause between each move. */
  protected int sleepTime = 250;
  /** The direction for this particular sprite. */
  protected int direction;
  /** The direction for going across the page */
  public static final int HORIZONTAL = 1;
  /** The direction for going up and down */
  public static final int VERTICAL = 2;
  /** The direction for moving diagonally */
  public static final int DIAGONAL = 3;

  /** Construct a Sprite with a Component parent, image and direction.
   * Construct and start a Thread to drive this Sprite.
   */
  public Sprite(Component parent, Image img, int dir) {
    super();
    this.parent = parent;
    this.img = img;
    switch(dir) {
      case VERTICAL: case HORIZONTAL: case DIAGONAL:
        direction = dir;
        break;
      default:
        throw new IllegalArgumentException(
          "Direction " + dir + " invalid");
    }
    setSize(img.getWidth(this), img.getHeight(this));
  }

  /** Construct a sprite with the default direction */
  public Sprite(Component parent, Image img) {
    this(parent, img, DIAGONAL);
  }

  /** Start this Sprite's thread. */
  public void start() {
    t = new Thread(this);
    t.setName("Sprite #" + ++spriteNumber);
    t.start();
  }

  /** Stop this Sprite's thread. */
  public void stop() {
    if (t == null)
      return;
    System.out.println("Stopping " + t.getName());
    done = true;
  }

  /** Adjust the motion rate */
  protected void setSleepTime(int n) {
    sleepTime = n;
  }

  /**
   * Run one Sprite around the screen.
   * This version just moves them around either across, down, or
   * at some 45-degree angle.
   */
    public void run() {
    int width = parent.getSize().width;
    int height = parent.getSize().height;
    // Set initial location
    x = (int)(Math.random() * width);
    y = (int)(Math.random() * height);
    // Flip coin for x & y directions
    int xincr = Math.random()>0.5?1:-1;
    int yincr = Math.random()>0.5?1:-1;
    while (!done) {
      width = parent.getSize().width;
      height = parent.getSize().height;
      if ((x+=xincr>= width)
        x=0;
      if ((y+=yincr>= height)
        y=0;
      if (x<0)
        x = width;
      if (y<0)
        y = height;
      switch(direction) {
        case VERTICAL:
          x = 0;
          break;
        case HORIZONTAL:
          y = 0;
          break;
        case DIAGONAL: break;
      }
      //System.out.println("from " + getLocation() + "->" + x + "," + y);
      setLocation(x, y);
      repaint();
      try {
        Thread.sleep(sleepTime);
      catch (InterruptedException e) {
        return;
      }
    }
  }

  /** paint -- just draw our image at its current location */
    public void paint(Graphics g) {
    g.drawImage(img, 00this);
    }
}
/**
* Java Code from Java Cookbook, Second Edition
* By Ian F. Darwin
* Second Edition June 2004
* Series: Cookbooks
* ISBN: 0-596-00701-9
* Details: http://www.oreilly.com/catalog/javacook2/index.html
* Copyright (c) Ian F. Darwin, http://www.darwinsys.com/, 1996-2002.
* All rights reserved. Software written by Ian F. Darwin and others.
* $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
*/



References.

The list of classes which were used on this page you can find below. The links to Java API contain official SUN documentation about all used classes.

  java.awt.MediaTracker

  java.applet.Applet

  java.awt.event.ActionListener

  java.awt.Panel

  java.awt.Image

  java.util.Vector

  java.awt.Button

  java.awt.BorderLayout

  java.lang.InterruptedException

  java.lang.IllegalArgumentException

  java.awt.event.ActionEvent

  java.awt.Component

  java.lang.Runnable

  java.lang.Thread

  java.util.Set

  java.awt.Graphics




[ Go Back ]



Home Code Examples Java Forum All Java Tips Books Submit News, Code... Search... Offshore Software Tech Doodling

RSS feed Java FAQ RSS feed Java FAQ News     

    RSS feed Java Forums RSS feed Java Forums

All logos and trademarks in this site are property of their respective owner. The comments are property of their posters, all the rest 1999-2006 by Java FAQs Daily Tips.

Interactive software released under GNU GPL, Code Credits, Privacy Policy