title: java 2D and swing
body: <p>I have trouble understanding a fundamental concept in Java 2D.<br>
  To give a specific example:<br>
  One can customize a swing component via implementing it's own version of the method <code>paintComponent(Graphics g)</code><br>
  Graphics is available to the body of the method.<br>
  Question:<br>
  What is exactly this Graphics object, I mean how it is related to the object that has the method <code>paintComponent</code>? Ok, I understand that you can do something like:</p>
  
  <pre><code>g.setColor(Color.GRAY);
  g.fillOval(0, 0, getWidth(), getHeight());
  </code></pre>
  
  <p>To get a gray oval painted. What I can not understand is how is the Graphics object related to the component and the canvas. How is this drawing actually done?<br>
  Another example:  </p>
  
  <pre><code>public class MyComponent extends JComponent {
  
       protected void paintComponent(Graphics g) {
  
                  System.out.println("Width:"+getWidth()+", Height:"+getHeight());
  
              }
  
      public static void main(String args[]) {
  
                  JFrame f = new JFrame("Some frame");
                  f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                  f.setSize(200, 90);
                  MyComponent  component = new MyComponent  ();
                  f.add(component);
                  f.setVisible(true);       
            }
   }
  </code></pre>
  
  <p>This prints </p>
  
  <blockquote>
    <p>Width:184, Height:52</p>
  </blockquote>
  
  <p>What does this size mean? I have not added anything to the frame of size(200,90).  </p>
  
  <p><strong>UPDATE:</strong><br>
  I understand that I must override paint to give in the <code>Graphics g</code> object the hints required to do the repaint and that I do not have to create a <code>Graphics</code> object as one will be given by platform.<br>
  What happens after that is what I can not understand.<br>
  E.g. does <code>Graphics</code> represent the screen and the object is painted accordingly on screen as soon as I start calling the various <code>g.setXXX</code> methods?<br>
  Does it get stored in a queue and there is a 1-1 association among <code>g</code> and each <code>component</code>? So the framework uses each <code>g</code> of each component to paint it one at a time?<br>
  How does this work?
  Any help on this is highly welcome</p>
  
  <p>Thanks</p>