import java.awt.Color;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String args[]) {
Mywindow win = new Mywindow();
new Ball(20, 20, win);
new Ball(300, 20, win);
new Ball(100, 200, win);
win.runFrame();
}
}
class Mywindow extends Frame {
List<Ball> balls = new ArrayList<Ball>();
Mywindow() {
setBackground(Color.black);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
setSize(350, 350);
setVisible(true);
}
public void runFrame() {
Thread t = new Thread(new MoveThread());
t.start();
}
public void setBalls(List<Ball> balls) {
this.balls = balls;
}
public void addBall(Ball ball) {
this.balls.add(ball);
}
public void paint(Graphics g) {
for (Ball b : balls) {
b.draw(g);
}
super.paint(g);
}
class MoveThread implements Runnable {
@Override
public void run() {
while (true) {
repaint();
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
class Ball {
int rgb = 0;
Color color;
int x, y;
int dx = 5, dy = 5;
Mywindow win;
Ball(int x, int y, Mywindow win) {
this.x = x;
this.y = y;
this.win = win;
win.addBall(this);
}
public void doColor() {
rgb = (int) (Math.random() * 0xFFFFFF);
color = new Color(rgb);
}
public void draw(Graphics g) {
Color c = g.getColor();
g.setColor(color);
g.fillOval(x, y, 50, 50);
g.setColor(c);
move();
}
public void move() {
if (x <= 0) {
dx = 5;
doColor();
} else if ((x + 50) >= win.getWidth()) {
dx = -5;
doColor();
}
if (y <= 30) {
dy = 5;
doColor();
} else if ((y + 50) >= win.getHeight()) {
dy = -5;
doColor();
}
x = x + dx;
y = y + dy;
}
}