Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Applet/ Animation/ repaint-update-paint ?

 
Gilbert Baron
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This code is from the book by Xiaoping Jia "Object-Oriented Software Development using Java.
It presents an idiom for creating animation applets using double buffering.
I am having a bit of trouble understanding one part. TI is the part where the paint method calls update.
Why is this not a loop.
Is it not true that ;
repaint calls--> update calls---> paint in Java?
It that is true, why does paint call update here? Why is it not a never ending loop?
If it is not true, how does paint ever get called in the first place? There is no call to it in the code here.
The code does work, so obviously I am missing something. Probably in the overridden repaint method which I can't see.

CODE FOLLOWS:
import java.awt.*;

public class BouncingBall
extends java.applet.Applet implements Runnable {
protected Color color = Color.green;
protected int radius = 20;
protected int x, y;
protected int dx = -2, dy = -4;
protected Image image;
protected Graphics offscreen;
protected Dimension d;
public void init() {
String att = getParameter("delay");
if (att != null) {
delay = Integer.parseInt(att);
}
d = getSize();
x = d.width * 2 / 3;
y = d.height - radius;
}

public void update(Graphics g) {
// create the off-screen image buffer
// if it is invoked the first time
if (image == null) {
image = createImage(d.width, d.height);
offscreen = image.getGraphics();
}
// draw the background
offscreen.setColor(Color.white);
offscreen.fillRect(0,0,d.width,d.height);
// adjust the position of the ball
// reverse the direction if it touches
// any of the four sides
if (x < radius | | x > d.width - radius) {
dx = -dx;
}
if (y < radius | | y > d.height - radius) {
dy = -dy;
}
x += dx;
y += dy;
// draw the ball
offscreen.setColor(color);
offscreen.fillOval(x - radius, y - radius,
radius * 2, radius * 2);
// copy the off-screen image to the screen
g.drawImage(image, 0, 0, this);
}
public void paint(Graphics g) {
update(g);
}
// The animation applet idiom
protected Thread bouncingThread;
protected int delay = 100;
public void start() {
bouncingThread = new Thread(this);
bouncingThread.start();
}
public void stop() {
bouncingThread = null;
}
public void run() {
while (Thread.currentThread() == bouncingThread) {
try {
Thread.currentThread().sleep(delay);
} catch (InterruptedException e) {}
repaint();
}
}
}

------------------
"Hierro candente, batir de repente"
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic