views:

107

answers:

2

I'm having a problem adding a JPanel on top of an Image. This is what I'm trying to do:

Image bgImage = loadImage(filename);
JPanel jp = new JPanel();

jp.setBounds(100,100,100,100);
jp.setOpaque(true);
jp.setBackgroudColor(Color.red);

bgImage.add(jp);

After doing this, I only see the bgImage. I tried everything but I still can't show the panel. Can somebody help me?

+2  A: 

You cannot place a component inside an Image. What you want to do is paint the Image onto the background of a swing component (like JPanel). All swing components have a paint() method that calls these three methods (perhaps not quite this order): paintComponent(), paintChildren(), paintBorder(). So, you want to override the paintComponent() method to paint your background image over the panel. When this runs, your custom method will be called, and then the paintChildren() method will be called, which will paint all "child" components over the top of your background image:

class BackgroundImagePanel extends JPanel {

    public void setBackgroundImage(Image backgroundImage) {
        this.backgroundImage = backgroundImage;
    }

    @Override
    protected void paintComponent(Graphics graphics) {
        super.paintComponent(graphics);
        graphics.drawImage(backgroundImage, 0, 0, this);
    }

    private Image backgroundImage;
}

BackgroundImagePanel panel = new BackgroundImagePanel();
panel.setBackgroundImage(image);
panel.add(new JTextField("Enter text here..."));
panel.add(new JButton("Press Me"));
SingleShot
uhm, sorry if my code is such a trash. i have a longer code that's working (not the one on top). But i really need to place the panel on top of the image, because from there i will be placing swing components...simply put, i want an Image as my background, an 'invisible' panel on top, and swing components last. :|
annaoj
OK, understood. I have edited my answer to be more descriptive.
SingleShot
A: 

The "BackgroundImagePanel" solution paints the image at its actual size. If this is a requirement, then you can just use a JLabel instead of creating a custom component.

The BackgroundPanel entry shows how you can do this. It also provides a background panel with more custom image painting solutions, that will allow you to scale and tile the image, if this is part of your requirement.

camickr