0

I'm trying to overlay a background picture with a .png sample, and I don't know how it works. I tried to create 2 JPanels, but didn't find out how to overlay them, then I tried to create 2 JLabels and once again, they just stay separated.

Have you any idea ? Thanks !

user3240711
  • 31
  • 1
  • 3
  • What _exactly_ do you mean _"overlay"_? Please explain more clearly and also show us your attempt and where you're having problems. – Paul Samsotha Feb 09 '14 at 11:08

1 Answers1

0

You can use one jPanel.Override paint or paintComponent method and draw your picture with graphic object.

    public class MyCustomPanel extends JPanel{

    private Image img;

    public MyCustomPanel(// use constructor to get img or load it directly from below){
     //load image
    } 

    public void paintComponent(Graphics g)
        {
            super.paintComponent(g);
            // Draws the img to the BackgroundPanel.
            g.drawImage(img, 0, 0, this);
        }


}

Then you can go to your main class and use this JPanel

MyCustomPanel mcp=new MyCustomPanel(//img path);
mcp.add(new JLabel("Hello"),BorderLayout.CENTER);
add(mcp),BorderLayout.CENTER);

//etc

I hope you understand

Next time post some code if you want to have answr faster and more complex/better suited for your case.

Tomas Bisciak
  • 2,801
  • 5
  • 33
  • 57
  • 1
    `g.drawImage(img, 0, 0, null);` should be `g.drawImage(img, 0, 0, this);`. Every [`Component`](http://docs.oracle.com/javase/7/docs/api/java/awt/Component.html) **is an** [`ImageObserver`](http://docs.oracle.com/javase/7/docs/api/java/awt/image/ImageObserver.html), so we might as well use it as such. – Andrew Thompson Feb 09 '14 at 12:55
  • 1
    Oh, plus the answer breaks the painting chain. It should override `paintComponent`, and immediately call the `super` method.. – Andrew Thompson Feb 09 '14 at 12:56
  • 1
    "Swing programs should override `paintComponent()` instead of overriding `paint()`."—[*Painting in AWT and Swing: The Paint Methods*](http://www.oracle.com/technetwork/java/painting-140037.html#callbacks), for [example](http://stackoverflow.com/a/2658663/230513). – trashgod Feb 09 '14 at 13:28
  • Thank you guys for pointing out mistakes !:) fixed .Wasnt sure which one shoud be called at first trashgod thx for explaining:).Im glad that i learn even from my answers :D – Tomas Bisciak Feb 09 '14 at 15:55