import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.geom.Ellipse2D;
/** spostamento del cerchio lungo l'asse x */
public class BouncingCircle extends Applet implements Runnable {
int x = 10, y = 40, r = 10; // posizione e raggio del cerchio
int dx = 20, dy = 0; // traiettoria del cerchio
Color endColor = Color.RED; // where we end
Color startColor = Color.YELLOW; // where we start
Color currentColor = startColor;
float fraction = 0;
Thread animator; // thread animazione
volatile boolean pleaseStop; // finire l'operazione
/** cerchio iniziale */
public void paint(Graphics g) {
// g.setColor(Color.yellow);
g.setColor(currentColor);
g.fillOval(x - r, y - r, r * 2, r * 2);
}
/**
* Questo metodo muove il cerchio e lo ridisegna.
* Thread animazione richiama questo metodo periodicamente.
*/
public void animate() {
// rimbalza se si colpisce una superficie.
Rectangle bounds = getBounds();
if ((x - r + dx < 0) || (x + r + dx > bounds.width))
dx = -dx;
if ((y - r + dy < 0) || (y + r + dy > bounds.height))
dy = -dy;
fraction += 0.04;
if (fraction >= 1) fraction = 0;
// interpolate between start and end colors with current fraction
int red = (int)(fraction * endColor.getRed() +
(1 - fraction) * startColor.getRed());
int green = (int)(fraction * endColor.getGreen() +
(1 - fraction) * startColor.getGreen());
int blue = (int)(fraction * endColor.getBlue() +
(1 - fraction) * startColor.getBlue());
currentColor = new Color(red, green, blue);
// muove il cerchio.
x += dx;
y += dy;
// chiede al browser il richiamo del metodo paint() per ridisegnare il cerchio nella sua nuova posizione.
repaint();
}
/**
* This method is from the Runnable interface. It is the body of the thread
* that performs the animation. The thread itself is created and started in
* the start() method.
*/
public void run() {
while (!pleaseStop) { // Loop until we're asked to stop
animate(); // Update and request redraw
try {
Thread.sleep(100);
} // 100 millisecondi di attesa in ogni frame
catch (InterruptedException e) {
} // Ignore interruptions
}
}
/** Start animating when the browser starts the applet */
public void start() {
animator = new Thread(this); // Create a thread
pleaseStop = false; // Don't ask it to stop now
animator.start(); // Start the thread.
// The thread that called start now returns to its caller.
// Meanwhile, the new animator thread has called the run() method
}
/** Stop animating when the browser stops the applet */
public void stop() {
// Set the flag that causes the run() method to end
pleaseStop = true;
}
}