title: java drawing on JPanel with timer/delay
body: <p>I'm trying to make a small Mosaic programm, that draws squares randomly all over the JPanel. I want to make it so, that it draws every 0,2 sec 1 square (not all at once), but so far i can make only it to draw all at once with a while loop. I have tried with ActionListener and Timer, but i found out, that i cant pass the same Graphics g to ActionListener. Then i tried with Thread.Sleep(200) but then the app froze. Now i have tried with System.currentTimeMillis(); but its same as with Threads... Searched all over the internet but didnt find anything that works.</p>
  
  <p>Main:</p>
  
  <pre><code>import javax.swing.JApplet;
  
  
  public class Main extends JApplet{
  public void init(){
      setSize(500, 300);
      Mosaic mosaic = new Mosaic();
  
      setContentPane(mosaic);
  
  }
  }
  </code></pre>
  
  <p>App:</p>
  
  <pre><code>import java.awt.Color;
  import java.awt.Graphics;
  import java.util.Random;
  import javax.swing.JPanel;
  
  public class Mosaic extends JPanel{
  
  private int width, height;
  private int ruut; // square 
  private int w = width / 2, h = height / 2; // middle of the app 
  
  Random rand = new Random();
  Color color;
  
  public Mosaic(){
      this(500, 300, 10);     
  }
  
  public Mosaic(int width, int height, int ruut){
      this.width = width;
      this.height = height;
      this.ruut = ruut;       
      setBackground(Color.BLACK);     
  }
  
  public void paintComponent(Graphics g){
      super.paintComponent(g);    
      //draws random squares
      while (true) {
          moveNext(g);
          wait(200);
      }
  }
  
  //delay n millisec
  public void wait(int n){
      long t0, t1;
      t0 = System.currentTimeMillis();
  
      do {
          t1 = System.currentTimeMillis();            
      } while ((t1 - t0) &lt; n);
  }   
  
  //next square
  public void moveNext(Graphics g){       
  
      int r = rand.nextInt(4);        
  
      switch (r) {
      case 1:
          h += ruut;
          wallTest();
          break;
      case 2:
          h -= ruut;
          wallTest();
          break;
      case 3:
          w -= ruut;
          wallTest();
          break;
      case 4:
          w -= ruut;
          wallTest();
          break;
      }
  
      color = new Color(0, rand.nextInt(255-50)+50, 0);
      g.setColor(color);
      g.fillRect(w, h, ruut, ruut);       
  }
  
  public void wallTest(){
      if (h &gt; height){
          h = 0;
      }
      if (h &lt; 0){
          h = height;
      }
      if (w &gt; width){
          w = 0;
      }
      if (w &lt; 0){
          w = width;
      }
  }   
  </code></pre>
  
  <p>}</p>