title: Java - using paintComponent for graphics, calling functions from within?
body: <p>I'm really confused with the program flow for how the <code>paintComponent</code> function works within my <code>JPanel</code>. Ideally I'd like to have access to the Graphics object to draw stuff from other functions based on my program flow. I'm thinking along the lines of the following: </p>
  
  <pre><code>private Graphics myG;
  
  public void paintComponent(Graphics g) {
      super.paintComponent(g);
      myG = g; //I want a graphics object that I can just draw with. 
               //Should I just initialize to myG = new Graphics(); or something?
      //private Graphics myG = new Graphics(); does not seem to work        
    }
  
  //this is what's getting called, where I want to call other functions that 
  //can use myG to draw graphics as I please
  public void startPanelView() {      
  
      myG.drawRect(350, 20, 400, 300); //doesn't work
  
      otherFunctionForGraphics(); //which will also use myG.  
  }
  </code></pre>
  
  <p>I hope I've made myself clear here. I just want to be able to do use the Graphics class as I please. Currently I can only do stuff like <code>g.drawRect(...)</code> inside of the <code>paintComponent()</code> function. This could work for my purposes but I'd like more flexibility. </p>
  
  <p>Thanks. </p>
  
  <p>EDIT - Alright, I understand that I should not try and reference a Graphics object outside. But how should I go about separating application logic from the paintComponent function? Right now this class is looking a little messy because I have the following: </p>
  
  <pre><code>public void paintComponent(Graphics g) {
  
      if (flag1 == true) {
          //do some graphics stuff, that I would prefer to be in another function
      }
  
      if (flag2 == true) {
          //do some other graphics stuff, again, which I would prefer 
          //to be in another function
      }
  
      //... etc. More of these cases.
  }
  </code></pre>
  
  <p>And basically the paintComponent function is getting stupidly long and complicated for me, so I would like to break it up in whatever ways possible. </p>