// <applet code="BB" width="400" height="400"></applet>
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.*;
import javax.imageio.ImageIO;
public class BB extends Applet implements Runnable {
private BufferedImage img;
private Image offscreenImage;
private Graphics offscr;
private Thread t;
private boolean showImage;
int width;
int height;
boolean animate = false;
// No Ball class -> improvise:
private Point loc = new Point();
int xSpeed = 3;
int ySpeed = 2;
public void init() {
showImage = true;
try {
String path = "images/geek/geek-----.gif";
//"right0.gif"
URL imageLocation = new URL(getCodeBase(), path);
img = ImageIO.read(imageLocation);
} catch (IOException e) {
System.out.println("image loading failed: " + e.getMessage());
}
addMouseListener(ma);
}
public void run() {
while (animate) {
checkCollisions();
loc.x += xSpeed;
loc.y += ySpeed;
offscr.setColor(Color.white);
offscr.fillRect(0, 0, width, height);
offscr.setColor(Color.black);
offscr.drawRect(0, 0, width - 1, height - 1);
if (showImage)
offscr.drawImage(img, loc.x, loc.y, this);
else
offscr.fillRect(loc.x, loc.y, 20, 20);
repaint();
try {
t.sleep(100);
} catch (InterruptedException e) {
animate = false;
}
}
}
public void start() {
while(getWidth() <= 0 || getHeight() <= 0) {
try {
Thread.sleep(25);
} catch (InterruptedException e) {
System.out.println("startup error");;
}
}
width = getSize().width;
height = getSize().height;
if(offscreenImage == null) {
offscreenImage = createImage(width, height);
offscr = offscreenImage.getGraphics();
}
animate = true;
t = new Thread(this);
t.start();
}
public void stop() {
animate = false;
if(t != null)
t.interrupt();
t = null;
}
public void paint(Graphics g) {
g.drawImage(offscreenImage, 0, 0, this);
}
public void update(Graphics g) {
paint(g);
}
private void checkCollisions() {
int w = showImage ? img.getWidth() : 20;
int h = showImage ? img.getHeight() : 20;
if (loc.x + xSpeed <= 0 || loc.x + w + xSpeed >= width)
xSpeed *= -1;
if (loc.y + ySpeed < 0 || loc.y + h + ySpeed >= height)
ySpeed *= -1;
}
private MouseListener ma = new MouseAdapter() {
public void mousePressed(MouseEvent e) {
showImage = !showImage;
}
};
}