title: Paint background of JPanel
body: <p>How can I tell the paint method to draw background on JPanel only and not on the entire JFrame.
  My JFrame size is bigger than the JPanel. When I try to paint a grid background for the JPanel, the grid seems to be painted all over the JFrame instead of just the JPanel. </p>
  
  <p>Here parts of the code:</p>
  
  <pre><code>public class Drawing extends JFrame {
    JPanel drawingPanel;
    ...........
    public Drawing (){
      drawingPanel = new JPanel();
      drawingPanel.setPreferredSize(new Dimension(600,600));
    }
  
  
  public void paint(Graphics g) 
  {
    super.paintComponents(g);
    Graphics2D g2 = (Graphics2D) g;
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
  
    paintBackground(g2); //call a METHOD to paint the for JPANEL
  }
  
  
  private void paintBackground(Graphics2D g2)
  {
    g2.setPaint(Color.GRAY);
    for (int i = 0; i &lt; drawingPanel.getSize().width; i += 300) 
    {
       Shape line = new Line2D.Float(i, 0, i, drawingPanel.getSize().height);
       g2.draw(line);
    }
  
    for (int i = 0; i &lt; drawingPanel.getSize().height; i += 300) 
    {
      Shape line = new Line2D.Float(0, i, drawingPanel.getSize().width, i);
      g2.draw(line);
    }      
  } //END private void paintBackground(Graphics2D g2)
  
  }
  </code></pre>