Reputation: 11
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
Upvotes: 1
Views: 343
Reputation: 324118
By default components have a size of (0, 0) so there is nothing to paint.
You need to override the getPreferredSize()
method of your CustomPanel
to return the size of the image.
Then the layout manager can use this information the to set the size and location of the panel.
However, since you are just painting the image at its actual size, then another solution is to just add an ImageIcon to a JLabel and add the label to the panel. Custom painting is only necessary if you plan to alter the image, maybe by scaling it to fit the size of the panel as it changes.
See Background Panel for more information and examples.
Upvotes: 1
Reputation: 676
Two things could be wrong that I can see :
Toolkit.getDefaultToolkit().getImage(filename)
. So as @Berger mentionned, I would print out the exception;MainPanel
container not properly set, we do not see that part of the code so I would verify it.To see a working example see How do I draw an image to a JPanel or JFrame?
Upvotes: 0