Hello,
The following is a bouncing ball applet. When I do double buffering (variables, g1 and image), I still see the flickering . I would be grateful for any help.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.lang.Thread;
public class Ball_Bounce extends JApplet implements Runnable
{
private Thread blueBall, redBall;
private boolean xUp, yUp, xUp1, yUp1;
private int x, y, xDx, yDy;
private final int MAX_X = 500, MAX_Y = 500;
private boolean flag = true;
private Graphics g1;
private Image image;
public void init()
{
xUp = false;
yUp = false;
xDx = 1;
yDy = 1;
image = createImage(500, 500);
g1 = image.getGraphics();
createBall();
}
public void createBall()
{
x = 300;
y = 250;
redBall = new Thread(this);
redBall.start();
}
public void paint( Graphics g )
{
super.paint( g );
g1.setColor (Color.gray);
g1.clearRect (0, 0, 500, 500);
g1.setColor (Color.RED);
g1.fillOval (x, y, 50, 50);
g.drawImage(image,0,0,this);
}
public void run()
{
while ( flag == true )
{
try
{
redBall.sleep(10);
}
catch ( InterruptedException exception )
{
System.err.println( exception.toString() );
}
if ( y <= 0 ) {
yUp = true;
yDy = ( int ) ( Math.random() * 5 + 2 );
}
else if ( y >= MAX_Y - 50 ) {
yDy = ( int ) ( Math.random() * 5 + 2 );
yUp = false;
}
if ( x <= 0 ) {
xUp = true;
xDx = ( int ) ( Math.random() * 5 + 2 );
}
else if ( x >= MAX_X - 50 ) {
xUp = false;
xDx = ( int ) ( Math.random() * 5 + 2 );
}
if ( xUp == true )
x += xDx;
else
x -= xDx;
if ( yUp == true )
y += yDy;
else
y -= yDy;
repaint();
}
}
}
Thank you!