-1

I've got problem with my JPanel background. I want to put my image "aaa.jpg" in to background of panel "p5". It will be good if it will be done without creating any new class. Is it simple way to set this image on background of my panel? Here's part of my code:

glowny4.setLayout(new GridLayout(1,2));
    glowny4.add (p5);
    glowny4.add (p6);  
mKorbel
  • 109,525
  • 20
  • 134
  • 319
Martyn
  • 21
  • 3

1 Answers1

3

There are two main ways I know of to make an image show in the background of a JPanel:

  • Use a JLabel instead of a JPanel,
    • simply make the Image into an ImageIcon
    • pass it into the JLabel via its setIcon(myIcon) method.
    • Make sure to give the JLabel a decent layout manager though.
    • This is the easiest way to implement this, but requires that the image can't scale to a different size if need be.
  • Use a JPanel and overwrite its paintComponent(...) method.
    • be sure to call the super method first inside of your override.
    • Then call g.drawImage(...) passing in your BufferedImage to this method.
    • This works well when the image needs to scale to a different size.

Please search this site as much has been posted on this before with sample code, some of it mine.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373