title: Random background color in a loop (Java)
body: <p>I want to change the background color of a panel each time repaint() is called. I'm having a hard time doing it with setBackground, so I wonder if a drawRect with the same dimensions as the frame will do the same job, or is this a no-no?</p>
  
  <pre><code>public class Artwork extends JPanel implements Runnable {
  
  boolean running = false;
  Random rng = new Random();
  
  public Artwork() {
      this.setOpaque(true);
  }
  
  public void Start() {
      running = true;
      Thread thread = new Thread(this);
      thread.start();
  }
  
  public void Stop() {
      running = false;
  }
  
  public void run() {
      while (running = true) {
          repaint();
          try {
              Thread.sleep(2500);
          } catch (InterruptedException e) {
              e.printStackTrace();
          }
      }
  }
  
  public void paintComponent(Graphics g) {
      super.paintComponent(g);
      super.setBackground(randomColor());
  }
  
  public Color randomColor() {
      int r = rng.nextInt(255);
      int g = rng.nextInt(255);
      int b = rng.nextInt(255);
      return new Color(r, g, b);
  }
  </code></pre>
  
  <p>With this the background color changes rapidly regardless of Thread.sleep</p>