import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
public class Ball extends JPanel{
Graphics g;
int rval; // red color value
int gval; // green color value
int bval; // blue color value
private int x = 1;
private int y = 1;
private int dx = 2;
private int dy = 2;
public void paintComponent(Graphics g){
for(int counter = 0; counter < 100; counter++){
// randomly chooses red, green and blue values changing color of ball each time
rval = (int)Math.floor(Math.random() * 256);
gval = (int)Math.floor(Math.random() * 256);
bval = (int)Math.floor(Math.random() * 256);
super.paintComponent(g);
g.drawOval(0,0,30,30); // draws circle
g.setColor(new Color(rval,gval,bval)); // takes random numbers from above and creates RGB color value to be displayed
g.fillOval(x,y,30,30); // adds color to circle
move(g);
}
} // end paintComponent
public void move(Graphics g){
g.fillOval(x, y, 30, 30);
x += dx;
y += dy;
if(x < 0){
x = 0;
dx = -dx;
}
if (x + 30 >= 400) {
x = 400 - 30;
dx = -dx;
}
if (y < 0) {
y = 0;
dy = -dy;
}
if (y + 30 >= 400) {
y = 400 - 30;
dy = -dy;
}
g.fillOval(x, y, 30, 30);
g.dispose();
}
} // end Ball class