I am trying to change the color of the ball when it hits any side of the wall. I can make it change color but it goes back to the original color afterwards.
This is the section of code I'm dealing with. I need some help. Is there a way to keep the color change?
If you go all the way down the code you can see the comment part //initial ball color. I am sure that part of the code is the reason why it goes back to the original color and does not change color. Is there a way to keep the color that it changes too when it hits the wall?
public void paint (Graphics g) {
g.drawRect(rectLeftX, rectTopY,
rectRightX - rectLeftX, rectBottomY - rectTopY);
r=new Random();
for (int n = 1; n < 500 ; n++) {
Color backgroundColour = getBackground();
g.setColor(backgroundColour);
g.fillOval(x, y, diameter, diameter);
if (x + xChange <= rectLeftX)
{
xChange = -xChange;
g.setColor(new Color(r.nextInt(256),r.nextInt(256),r.nextInt(256)));
g.fillOval (x, y, diameter, diameter);
}
if(x+xChange + diameter >= rectRightX)
{
xChange = -xChange;
g.setColor(new Color(r.nextInt(256),r.nextInt(256),r.nextInt(256)));
g.fillOval (x, y, diameter, diameter);
}
if (y+yChange <= rectTopY)
{
yChange = -yChange;
g.setColor(new Color(r.nextInt(256),r.nextInt(256),r.nextInt(256)));
g.fillOval (x, y, diameter, diameter);
}
if(y + yChange + diameter >= rectBottomY)
{
yChange = -yChange;
g.setColor(new Color(r.nextInt(256),r.nextInt(256),r.nextInt(256)));
g.fillOval (x, y, diameter, diameter);
}
x = x + xChange;
y = y + yChange;
// initial ball color
g.setColor(get());
g.fillOval (x, y, diameter, diameter);
try {
Thread.sleep(50);
} catch (InterruptedException e) {
g.drawString("sleep exception", 20, 20);
}
}
}
