Spritepublic class Sprite extends Component implements RunnableA Sprite is one Image that moves around the screen on its own |
Fields Summary |
---|
protected static int | spriteNumber | protected Thread | t | protected int | x | protected int | y | protected Component | parent | protected Image | img | protected boolean | done | protected int | sleepTimeThe time in mSec to pause between each move. | protected int | directionThe direction for this particular sprite. | public static final int | HORIZONTALThe direction for going across the page | public static final int | VERTICALThe direction for going up and down | public static final int | DIAGONALThe direction for moving diagonally |
Constructors Summary |
---|
public Sprite(Component parent, Image img, int dir)Construct a Sprite with a Component parent, image and direction.
Construct and start a Thread to drive this Sprite.
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));
| public Sprite(Component parent, Image img)Construct a sprite with the default direction
this(parent, img, DIAGONAL);
|
Methods Summary |
---|
public void | paint(java.awt.Graphics g)paint -- just draw our image at its current location
g.drawImage(img, 0, 0, this);
| public void | run()Run one Sprite around the screen.
This version just moves them around either across, down, or
at some 45-degree angle.
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;
}
}
| protected void | setSleepTime(int n)Adjust the motion rate
sleepTime = n;
| public void | start()Start this Sprite's thread.
t = new Thread(this);
t.setName("Sprite #" + ++spriteNumber);
t.start();
| public void | stop()Stop this Sprite's thread.
if (t == null)
return;
System.out.println("Stopping " + t.getName());
done = true;
|
|