title: Creating a custom method to draw - Graphics 2D g2 is null
body: <p>I am trying to solve the following problem: Write a program that displays the Olympic rings. Color the rings in the Olympic colors. Provide a method drawRing that draws a ring of a given position and color.</p>
  
  <hr>
  
  <p>I am having a major issue with my understanding of how exactly objects of type Graphics work. I initially tried using<code>getGraphics()</code> to pass it as a parameter to the method however i learned that this method is typically avoided as null exceptions are likely to occur. So i read that you should override the <code>paintComponent</code> method in the component class? so i tried this by making a class containing the override and my <code>drawRing</code> method, making Graphics2D g2 an instance variable however i am still getting a null error once it is called upon in the first line of <code>drawRing</code>. I have been trying to figure something out for hours but I'm really not sure how to approach this problem to make the method have access to the frame in main and if there's an entirely different way i should be tackling it. Any help is much appreciated.</p>
  
  <hr>
  
  <p>Also, I would just like to note that I have not begun accounting for x and y coordinates as well as color in my <code>drawRing</code> method, I first want to make sure the program can access the method and that it can draw on the frame made in main first, afterwards I figure those details will be fairly simple.</p>
  
  <hr>
  
  <p>My Code:</p>
  
  <pre><code>import javax.swing.*;
  import java.awt.*;
  import java.applet.*;
  import java.awt.geom.*;
  public class test{
      public static class ringComponent extends JComponent{
          private Graphics2D g2;
          public void paintComponent(Graphics g){
              g2 = (Graphics2D) g;
          }
          public void drawRing(){
              g2.setColor(Color.RED);//Null error here
              Ellipse2D.Double circle = new Ellipse2D.Double(50, 50, 200, 200);
              g2.draw(circle);
          }
      }
      public static void main(String[] args){
          JFrame frame = new JFrame();
          final int FRAME_WIDTH = 800;
          final int FRAME_HEIGHT = 800;
          frame.setSize(FRAME_WIDTH,FRAME_HEIGHT);
          frame.setTitle("Olympic Rings");
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          ringComponent rc = new ringComponent();
          rc.drawRing();
          frame.add(rc);
          frame.setVisible(true);
      }
  }
  </code></pre>