title: Drawing Canvas on JFrame
body: <p>I'm trying to draw simple shapes with Canvas, in this class I've set the painting</p>
  
  <pre><code>public class Game extends Canvas{
      //FIELDS
      public int WIDTH  = 1024;
      public int HEIGHT = WIDTH / 16 * 9;
  
      //METHODS
      public void start(){
          Dimension size = new Dimension (WIDTH, HEIGHT);
          setPreferredSize(size);
          paint(null);
      }
  
      public void paint(Graphics g){
          g.setColor(Color.GREEN);
          g.fillRect(0, 0, WIDTH, HEIGHT);
          g.setColor(Color.BLACK);
          g.fillOval(100, 100, 30, 30);
      }
  }
  </code></pre>
  
  <p>And in this the Window</p>
  
  <pre><code>public class MainW {
  
  
      public static void main(String[] args) {
          Game ga = new Game();
          JFrame frame = new JFrame ();
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.setLocationRelativeTo(null);
          frame.add(ga);
          frame.setVisible(true);
          ga.start();
  
      }
  
  }
  </code></pre>
  
  <p>It works, but the JFrame is not adapting to the Canvas. I have to manually resize the window to see the objects. How can I pack it so that JFrame automatically encompasses the Canvas?</p>
  
  <p>EDIT:
  That's really weird. While frame.pack() is indeed essential, it's not enough.
  What I did was change the start method and turn it into a constructor, like that:</p>
  
  <pre><code>    public class Game extends Canvas{
          //FIELDS
          public int WIDTH  = 1024;
          public int HEIGHT = WIDTH / 16 * 9;
  
          //METHODS
          public void Game(){
          Dimension size = new Dimension (WIDTH, HEIGHT);
          setPreferredSize(size);
      }
  </code></pre>
  
  <p>then, from the other class, Eclipse complained about calling the constructor directly(E.G. ga.Game), so I followed it's tip and changed to:</p>
  
  <pre><code>    public static void main(String[] args) {
          Game ga = new Game();
          JFrame frame = new JFrame ();
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.setLocationRelativeTo(null);
          frame.add(ga);
          frame.setVisible(true);
          ga.getName();
  
      }
  </code></pre>
  
  <p>This way I achieve what I have in mind but I really don't know why I can't call the constructor.</p>