javaswingjpanel

How would I add a picture as a background directly to a JPanel


Is there any way to add a background without using a new JPanel?

I am making a dungeon themed minesweeper game in Java using Swing and need to have a different image as a background. My game consists of one main JFrame and the title screen, and the three difficulties as JPanels.

Adding a new Panel to add a background picture would be really difficult as it would mess with a lot of my code. I basically just want to "stick" the background to the back of the JPanel while also having it at a back layer, without covering any of the buttons.


Solution

  • This it how I did it. Overriding the paintComponent

    import java.awt.Graphics;
    import javax.swing.JPanel;
    import vokabeltrainer.common.ApplicationImages;
    
    public class TrashCanBackgroundPanel extends JPanel
    {
       private static final long serialVersionUID = -7918923007938243168L;
    
       @Override
       public void paintComponent(Graphics g)
       {
          super.paintComponent(g);
          if (ApplicationImages.getTrashcanBackground() != null)
          {
             int x = this.getParent().getWidth() / 2 - 1000 / 2;
             int y = this.getParent().getHeight() / 2 - 620 / 2;
             g.drawImage(ApplicationImages.getTrashcanBackground(), x, y, this);
          }
       }
    }
    

    The width of the image is 1000 pixel and the height 620 pixel.

    Just set the JPanels layered on top

    setOpaque(false)