简体   繁体   中英

Problems displaying GUI components with img background

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:

在此输入图像描述

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

在此输入图像描述

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM