JavaRanch Home    
 
This page:         last edited 31 July 2008         What's Changed?         Edit

Background Image On J Panel   

How do I paint an image as a background on a JPanel?

This question gets asked quite frequently in the Swing forum. There are different methods of doing this however this is the simplest and most common.


class BackgroundPanel extends JPanel
{
  Image image;
  public BackgroundPanel()
  {
    try
    {
      image = javax.imageio.ImageIO.read(new java.net.URL(getClass().getResource("Test.gif"), "Test.gif"));
    }
    catch (Exception e) { /*handled in paintComponent()*/ }
  }

  @Override
  protected void paintComponent(Graphics g)
  {
    super.paintComponent(g); 
    if (image != null)
      g.drawImage(image, 0,0,this.getWidth(),this.getHeight(),this);
  }
}


SwingFaq

JavaRanchContact us — Copyright © 1998-2014 Paul Wheaton