开发者

Layering JPanels with background image

I wanted to have a background image and two panels atop them. Learnt that JLayeredpane's are quite suitable. So I extended a JLayeredPane in my class and tried to draw the image from paint(). I got it working. But when I added other layers over it they weren't visible.

Again I thought of removing the bgimage from LayeredPane, added to the first layer above it(in JPanel). Now the image is not visible. Why does it happen? I wanted to do some thing like the screenshot I've provided. Pls help.

My code:

From my JFrame:

Container cp = this.getContentPane();
JLayeredPane backDropPanel = new JLayeredPane();    
cp.add(backDropPanel,BorderLayout.CENTER);
backDropPanel.add(new bgPanel(), new Integer(1),0);
backDropPanel.add(new itemScrollerPanel(), new Integer(1),0);

Panel's:

class bgPanel extends JPanel{
String imageLocation = "/home/phantom/Desktop/BackDrop3.jpg";
private Image bgImage;
bgPanel(){
    bgImage = new ImageIcon(imageLocation).getImage();
    setPreferredSize(new Dimension(800,500));
    setLayout(null);
    setOpaque(true);
}

public void paint(Graphics g){      
super.paint(g);
g.drawImage(bgImage,0,0,this);
}}

class开发者_如何学编程 itemScrollerPanel extends JPanel{
    itemScrollerPanel(){
    setBounds(0,100,200,200);
    setBackground(Color.RED);
    setOpaque(true);

}}

In this code I get to see the itemsScrollerPanels's RED BG drawn. But not the image of bgPanel class.

My requirement is something like this:

Layering JPanels with background image


Without setting your bgPanel size explicitly, I get

System.err.println(bgPanel.getSize());
//java.awt.Dimension[width=0,height=0]

If you change your code from

setPreferredSize(new Dimension(800, 500));

to

setPreferredSize(new Dimension(800, 500));
setSize(800,500);

You should see the panel painted.


Try to change the setOpaque() to false so that all the pixels of JPanel are not painted .Thus making it transparent.If you still cant do it,check whether the Jpanel is actually opaque or not using isOpaque()

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜