import java.awt.*; import java.awt.event.*; import java.util.Random; import javax.swing.*; public class ShapesApplet extends JApplet implements ActionListener { CircleFieldPanel jp; Timer timer; int speed=50;//msecs public void init() { Circle c1 = new RandomXYCircle(this.getSize().width/2,this.getSize().height/2,10,Color.red); Circle c2 = new RandomAngleCircle(this.getSize().width/2,this.getSize().height/2,10,Color.blue); jp = new CircleFieldPanel(c1, c2); jp.setBackground(Color.white); getContentPane().add(jp); timer = new javax.swing.Timer(speed,this); } public void start() { timer.start(); } public void actionPerformed(ActionEvent e) { jp.repaint(); } } class CircleFieldPanel extends JPanel { CircleFieldPanel(Circle c1, Circle c2) { this.c1 = c1; this.c2 = c2; } protected void paintComponent(Graphics g) { super.paintComponent(g); c1.draw(g, this.getSize()); c2.draw(g, this.getSize()); } private Circle c1; private Circle c2; }; abstract class Circle { int x; int y; int d; Color c; public Circle(int x, int y, int d, Color c) { this.x = x; this.y = y; this.d = d; this.c = c; } public void draw(Graphics g, Dimension dim) { g.setColor(Color.white); g.fillOval(x,y,d,d); updateXY(dim ); g.setColor(c); g.fillOval(x,y,d,d); } protected abstract void updateXY(Dimension dim); } class RandomXYCircle extends Circle { Random r; public RandomXYCircle(int x, int y, int d, Color c) { super(x,y,d,c); r = new Random(); } protected void updateXY(Dimension dim) { y += r.nextInt(d+1)-d/2; x += r.nextInt(d+1)-d/2; x = Math.max(0,Math.min(x,dim.width)); y = Math.max(0,Math.min(y,dim.height)); } } class RandomAngleCircle extends Circle { Random r; double angle; public RandomAngleCircle(int x, int y, int d, Color c) { super(x,y,d,c); r = new Random(); angle = r.nextDouble() * Math.PI *2; } protected void updateXY(Dimension dim) { angle += (r.nextDouble()-.5); //System.out.println("Angle " + angle); y += Math.sin(angle) * d/5; x += Math.cos(angle) * d/5; x = Math.max(0,Math.min(x,dim.width)); y = Math.max(0,Math.min(y,dim.height)); } }