title: (Java) repaint() executes at random times
body: <p>While working with GUI in Java, I have noticed that the <code>repaint()</code> method of <code>Component</code> class exhibits unusual behaviors. The code below updates the content pane after the printing of <code>1</code> and before <code>2</code>, or so was my intention.</p>
  
  <pre><code>public class ErrorTest {
  
      public static void main(String[] args) throws InterruptedException {
  
          JFrame F = new JFrame();
          F.setSize(100,100);
  
          Panel P = new Panel();
          F.setContentPane(P);
          F.setVisible(true);
  
          while(true) {
              System.out.println("\n1");
              P.repaint();
              System.out.println("2");
              Thread.sleep(100);
  
          }
      }
  }
  
  class Panel extends JPanel {
  
      @Override
      protected void paintComponent(Graphics G) {
          System.out.println("painted");
          G.drawOval(10, 10, 20, 30);
      }
  }
  </code></pre>
  
  <p>If <code>Thread.sleep(100);</code> is included, The output of this code is:</p>
  
  <pre><code>1
  2
  painted
  
  1
  2
  painted
  </code></pre>
  
  <p>and so on. If not, the output is:</p>
  
  <pre><code>1
  2
  
  1
  2
  painted
  </code></pre>
  
  <p>and so on, usually just printing <code>1</code> and <code>2</code> and rarely printing <code>painted</code> in random locations. The output I'm looking for is:</p>
  
  <pre><code>1
  painted
  2
  
  1
  painted
  2
  </code></pre>
  
  <p>repeated. It seems to be the case that this <code>update()</code> method is being called at the beginning of each iteration, regardless of where I actually write it. There also seems to be some delay before the method is executed. What can I do to achieve my desired output?</p>