I am trying to create a JPanel with a background image inside another JPanel but the background image is not showing up. How do I fix this?
public class CustomPanel extends JPanel{
Image img;
private final static String BACKGROUND = "images/background.png";
private void loadImage(String filename){
try{
img = Toolkit.getDefaultToolkit().getImage(filename);
} catch(Exception e){}
}
@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(this.img, 0, 0,null);//display this image as a background
Toolkit.getDefaultToolkit().sync();//makes animations smooth
}
public CustomPanel(){
this.setLayout(null);
this.loadImage(this.BACKGROUND);//prepare background image
this.repaint();//set bg image
}
}
This is the MainPanel which will hold other JPanels with background.
public class MainPanel extends JPanel{
public Container container;
public MainPanel(Container container){
this.setLayout(null);
this.container = container;
CustomPanel panel= new CustomPanel();
this.add(panel);
}
}
I have read other questions related to this and most of it are failure to set super.paintComponent(g). I have done this in my code so I don't really know what seems to be the problem