Simplest way to set image as JPanel background

Joshua Martin picture Joshua Martin · Oct 1, 2013 · Viewed 221.3k times · Source

How would I add the backgroung image to my JPanel without creating a new class or method, but simply by inserting it along with the rest of the JPanel's attributes?

I am trying to set a JPanel's background using an image, however, every example I find seems to suggest extending the panel with its own class.

I have been looking for a way to simply add the image without creating a whole new class and within the same method (trying to keep things organized and simple).

Here is an example of the method that sets my JPanel:

public static JPanel drawGamePanel(){
    //Create game panel and attributes
    JPanel gamePanel = new JPanel();
    Image background = Toolkit.getDefaultToolkit().createImage("Background.png");
    gamePanel.drawImage(background, 0, 0, null);
    //Set Return
    return gamePanel;
}

Answer

Sage picture Sage · Oct 1, 2013

I am trying to set a JPanel's background using an image, however, every example I find seems to suggest extending the panel with its own class

yes you will have to extend JPanel and override the paintcomponent(Graphics g) function to do so.

@Override
  protected void paintComponent(Graphics g) {

    super.paintComponent(g);
        g.drawImage(bgImage, 0, 0, null);
}

I have been looking for a way to simply add the image without creating a whole new class and within the same method (trying to keep things organized and simple).

You can use other component which allows to add image as icon directly e.g. JLabel if you want.

ImageIcon icon = new ImageIcon(imgURL); 
JLabel thumb = new JLabel();
thumb.setIcon(icon);

But again in the bracket trying to keep things organized and simple !! what makes you to think that just creating a new class will lead you to a messy world ?