I am trying to make an applet with a ball that bounces around the screen, and switches between being a black square and an image (right0.gif)
The square will bounce around just fine, but there isn't an image to go with it (I tested and it DOES throw an IOException in init() - ImageIO.read()).
import java.applet.Applet;
import java.awt.*;
import java.awt.image.*;
import java.io.*;
import java.net.*;
import javax.imageio.ImageIO;
public class BouncingBall extends Applet implements Runnable {
private BufferedImage img;
private Image offscreenImage;
private Graphics offscr;
private Thread t;
private boolean showImage;
private Ball ball;
private int width, height;
public void init() {
t = new Thread(this);
t.start();
showImage = true;
try {
URL imageLocation = new URL(getCodeBase(), "right0.gif");
img = ImageIO.read(imageLocation);
} catch (IOException e) {
}
width = getSize().width;
height = getSize().height;
offscreenImage = createImage(width, height);
offscr = offscreenImage.getGraphics();
ball = new Ball(0, 0, 5, 5);
}
public void run() {
while (true) {
repaint();
try {
t.sleep(30);
} catch (InterruptedException e) {
}
}
}
public void paint(Graphics g) {
ball.refresh();
checkCollisions();
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, ball.getX(), ball.getY(), this);
else
offscr.fillRect(ball.getX(), ball.getY(), 20, 20);
g.drawImage(offscreenImage, 0, 0, this);
}
public void update(Graphics g) {
paint(g);
}
private void checkCollisions() {
if (ball.getY() <= 0)
ball.setSpeedY(5);
if (ball.getY() + 20 >= height)
ball.setSpeedY(-5);
if (ball.getX() + 20 >= width)
ball.setSpeedX(-5);
if (ball.getX() <= 0)
ball.setSpeedX(5);
}
@SuppressWarnings("deprecation")
public boolean mouseDown(Event e, int x, int y) {
showImage = !showImage;
return true;
}
}
And I know that mouseDown is deprecated, I just haven't taken the time to learn how to use the Listeners.