title: Setting the width and height of a JComponent as instance variables
body: <p>I have a problem with setting the width and height of a component as instance variables (in the subclass of the component). If I call <code>getWidth()</code> and <code>getHeight()</code> in the constructor (which is always zero), the values are different from calling the same methods in <code>paintComponent(Graphics g)</code>. Can someone please explain why this is happening and how can I set the width and height of the component as instance variables. Thanks a lot in advance.</p>
  
  <p>Here is a code snippet:</p>
  
  <pre><code>import java.awt.Graphics;
  import javax.swing.JComponent;
  
  public class MyComponent extends JComponent
  {
      // Instance variables.
      private int width;
      private int height;
  
      public MyComponent()
      {
          width = getWidth();
          height = getHeight();
          System.out.println(width+","+height);
      }
  
      public void paintComponent(Graphics g)
      {
          // Local variables.
          int width = this.getWidth();
          int height = this.getHeight();
          System.out.println(width+","+height);
      }
  
  }
  </code></pre>
  
  <p>
  
  <pre><code>import javax.swing.JFrame;
  
  public class ComponentTester
  {
      public static void main(String args[])
      {
          JFrame frame = new JFrame();
          MyComponent component = new MyComponent();
  
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.setLocationRelativeTo(null);
          frame.setSize(350, 400);
          frame.setVisible(true);
  
          frame.add(component);
      }
  
  }
  </code></pre>