Hi, I am doing an assingment that creates an olympic ring image and makes it move. When it touch the window boundary, it will rebound in the same angle.
Here is my code:
CODE
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.awt.*;
/**
This class makes a rebound animation using the OlymipicRing object.
*/
public class OlympicRingRebound extends JApplet
{
/**
Sets up the applet.
*/
public void init()
{
setPreferredSize (new Dimension(WIDTH, HEIGHT));
setBackground(Color.white);
x = 0;
y = 0;
moveX = 3;
moveY = 4;
}
/*
Represents the action listener for the timer.
*/
class myTimer implements ActionListener
{
/*
Updates the position of the image and possibly the direction
of movement whenever the timer fires an action event.
*/
public void actionPerformed(ActionEvent event)
{
x += moveX;
y += moveY;
if (x <= 0 || x >= WIDTH - myOlympic.getWidth())
moveX = moveX * -1;
if (y <= 0 || y >= HEIGHT - myOlympic.getHeight())
moveY = moveY * -1;
repaint();
}
}
/*
Sets up the timmer and starts the animation when the applet starts.
*/
public void start()
{
ActionListener listener = new myTimer();
final int DELAY = 20; // Milliseconds between timer ticks
Timer t = new Timer(DELAY, listener);
t.start();
}
/*
Draws the image in the current location.
*/
public void paint(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
myOlympic = new OlympicRings(x, y);
myOlympic.draw(g2); // draw an olympic ring in x, y position
}
private int x;
private int y;
private int moveX;
private int moveY;
OlympicRings myOlympic;
public static final int WIDTH = 800, HEIGHT = 600;
}
OlympicRings class is omitted since it just draws an olympic ring.
The problems is that repaint() will update the new position, but the image with the old position is still there. How can I fix the problem?
Thank you.