Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Paint background of JPanel

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.

Here parts of the 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 < drawingPanel.getSize().width; i += 300) 
  {
     Shape line = new Line2D.Float(i, 0, i, drawingPanel.getSize().height);
     g2.draw(line);
  }

  for (int i = 0; i < 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)

}
like image 828
Jessy Avatar asked Feb 27 '23 20:02

Jessy


1 Answers

If you want to do painting on the JPanel then override the JPanel, not the JFrame.

You should be overriding the paintComponent() method of JPanel. Read the section from the Swing tutorial on Custom Painting for a working example.

like image 93
camickr Avatar answered Mar 06 '23 20:03

camickr