3

I've added a background to my Java Applet, I need some help understanding why the applet isn't displaying properly. To display this background image I've used the code seen below:

BufferedImage img = null;

try {
            URL url = new URL(getCodeBase(), "Backgrounds/Background.png");
            img = ImageIO.read(url);
        }
        catch (Exception e) {

        }

then also put this in the paint method...

public void paint(Graphics g) {
    g.drawImage(img, 0, 0, null);
}

The problem is that you cannot see the GUI components such as buttons and labels when the background is painted, even though the background is painted before the other GUI components are added to the content pane. It is possible to get the components to appear but you have to highlight them or click on them first.

This picture shows the applet when the applet is loaded:

enter image description here

Then this is the applet after I have clicked in a few places on screen:

enter image description here

JL9
  • 533
  • 3
  • 17
  • 1
    Why code an applet? If it is due to the teacher specifying it, please refer them to [Why CS teachers should **stop** teaching Java applets](http://programmers.blogoverflow.com/2013/05/why-cs-teachers-should-stop-teaching-java-applets/). – Andrew Thompson Apr 15 '15 at 19:55
  • Yeah it's a uni assignment, I don't have much choice really – JL9 Apr 15 '15 at 20:01

1 Answers1

3
public void paint(Graphics g) {
    g.drawImage(img, 0, 0, null);
}

Firstly, that method call should be:

public void paint(Graphics g) {
    g.drawImage(img, 0, 0, this); // Every Component is an image observer
}

Then, to fix the broken paint chain:

public void paint(Graphics g) {
    super.paint(g); // Draw the rest of the components!
    g.drawImage(img, 0, 0, this); // Every Component is an image observer
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • The other components aren't actually painted, they are just added to the content pane in a range of different methods, sorry I didn't make it too clear – JL9 Apr 15 '15 at 20:04
  • For better help sooner, post an [MCVE](http://stackoverflow.com/help/mcve) (Minimal Complete Verifiable Example) or [SSCCE](http://www.sscce.org/) (Short, Self Contained, Correct Example). – Andrew Thompson Apr 15 '15 at 20:23
  • @JL9 Sure, but paint is responsible for paint the child components, if you don't call super.paint, they won't be painted as part of the parent container... – MadProgrammer Apr 15 '15 at 21:03
  • @MadProgrammer I did try to put super.paint in and it didn't make a difference, the child components still displayed like the images above, where you have to highlight them to see them – JL9 Apr 15 '15 at 21:12
  • @jl9 Then, there is something else going on in your code that you're not showing us. You should also be checking to see img is null or not, as painting a null img is going to cause issues... – MadProgrammer Apr 15 '15 at 21:14