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) { }
}
@Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
if (image != null)
g.drawImage(image, 0,0,this.getWidth(),this.getHeight(),this);
}
}
SwingFaq