简体   繁体   中英

Putting a Panel on top of a JLabel backGround (Java)

I've been fruitlessly searching the internet and nothing that people suggest seems to have any effect for me.

I have a JFrame which I'm trying to put a JPanel in. That JPanel ideally would have a JLabel with an imageicon as the background and a set of buttons in its own Jpanel in the foreground. The issue is every type of layout manager I've seen suggested just does not work as advertised for me. The best I've gotten to work so far is this approach:

public MenuBackgroundPanel(AsteroidsFrame frame)
{
    this.gameFrame = frame;

    this.setLayout(new OverlayLayout(this));
    ImageIcon image = new ImageIcon(getClass().getResource("/resources/background1.gif"));
    imageLabel = new JLabel(image, JLabel.CENTER);
    mp = new MainMenuPanel(gameFrame);
    mp.setMaximumSize(new Dimension(300,200));

    this.add(mp);
    this.add(imageLabel);

    this.setVisible(true);
}

Unfortunately, I'm getting really strange alignments and trying to set location on the background (to actually get it to start at the JFrame's (0,0) or moving the button panel just seems to have no effect. Printing the location of each object says they're both at (0,0) but the image I'll link shows this is just not the case. My point is, I've tried things like JLayeredPane or setting the JLabel as the contentpane of the Jframe and making it transparent but nothing seems to do anything. One or the other of the two objects just covers the other completely.

http://i.imgur.com/ll5Y3j5.png

As you can see the objects are not at all aligned. Could anyone help me with this?

That JPanel ideally would have a JLabel with an imageicon as the background and a set of buttons in its own Jpanel in the foreground

Easiest way for something like this when the child panel is fully contained in the label image is to just set the layout manager of the JLabel and then add your components to the label.

JLabel background = new JLabel( new ImageIcon(...) );
background.setLayout( new GridBagLayout() );
JPanel buttons = new JPanel();
buttons.setOpaque( false );
buttons.add(...);
background.add(buttons, new GridBagConstraints() );

Now the button panel will be centered on the label.

As you can see the objects are not at all aligned

If you want to use the OverlayLayout then you need to play with the alignmentX/Y properties of each component. You would probably want to set them both to .5 . Check out: Java Layout with Component always in Top Right for an example of how changing these values can affect the layout.

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