import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class OvalDrawer extends JPanel implements Runnable{
  private Color[] colors={Color.RED,Color.BLACK,Color.BLUE,
                  Color.GREEN,Color.DARK_GRAY};
  private Color color;
  private int x=10,y=10,width=10,height=10;

  public OvalDrawer(){
    new Thread(this).start();
  }

  public void run(){
    while(true){
      x=(int)(Math.random()*300);
      y=(int)(Math.random()*300);
      width=(int)(Math.random()*100);
      height=(int)(Math.random()*100);
      color=colors[(int)(Math.random()*(colors.length-1))];
      repaint();
      try{Thread.sleep(400);}catch(InterruptedException e){throw new RuntimeException(e);}
    }
  }

  public void paintComponent(Graphics g){
    //调用父类的paintComponent(g)方法会导致先清空面板，使得上次所画的椭圆被删除。
    //super.paintComponent(g);  
    g.setColor(color);
    g.fillOval(x,y,width,height);  //画椭圆
  }
  public static void main(String args[]){
    JPanel panel=new OvalDrawer();
    JFrame frame=new JFrame("Hello");
    frame.setContentPane(panel);

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(300,300);
    frame.setVisible(true);

  }
}


/****************************************************
 * 作者：孙卫琴                                     *
 * 来源：<<Java面向对象编程>>                       *
 * 技术支持网址：www.javathinker.net                *
 ***************************************************/
