title: Best way to implement game loop without freezing UI thread
body: <p>I'm trying to make a simple 2D game in Java.</p>
  
  <p>So far I have a <code>JFrame</code>, with a menubar, and a class which extends <code>JPanel</code> and overrides it's <code>paint</code> method. Now, I need to get a game loop going, where I will update the position of images and so on. However, I'm stuck at how best to achieve this. Should I use multi-threading, because surely, if you put an infinite loop on the main thread, the UI (and thus my menu bar) will freeze up?</p>
  
  <p>Here's my code so far:</p>
  
  <pre><code>import java.awt.Color;
  import java.awt.Graphics;
  
  import javax.swing.JPanel;
  
  @SuppressWarnings("serial")
  public class GameCanvas extends JPanel {
  
      public void paint(Graphics g) {
          while (true) {
              g.setColor(Color.DARK_GRAY);
              try {
                  Thread.sleep(100);
              } catch (InterruptedException e) {
                  e.printStackTrace();
              }
          }
      }
  }
  
  import javax.swing.JFrame;
  import javax.swing.JMenu;
  import javax.swing.JMenuBar;
  import javax.swing.JMenuItem;
  
  @SuppressWarnings("serial")
  public class Main extends JFrame {
  
      GameCanvas canvas = new GameCanvas();
      final int FRAME_HEIGHT = 400;
      final int FRAME_WIDTH = 400;
  
      public static void main(String args[]) {
          new Main();
      }
  
      public Main() {
          super("Game");
  
          JMenuBar menuBar = new JMenuBar();
          JMenu fileMenu = new JMenu("File");
          JMenuItem startMenuItem = new JMenuItem("Pause");
          menuBar.add(fileMenu);
          fileMenu.add(startMenuItem);
  
          super.add(canvas);
          super.setVisible(true);
          super.setSize(FRAME_WIDTH, FRAME_WIDTH);
          super.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          super.setJMenuBar(menuBar);
      }
  }
  </code></pre>
  
  <p>Any pointers or tips? Where should I put my loop? In my main class, or my GameCanvas class?</p>