Search code examples
javaswingjpaneljlayeredpane

Using JLayeredPane to add multiple JPanels to a JPanel


I am trying to add multiple panels to another panel. I want them to be on top of each other so I'm using JLayeredPane. I've added a button to each one. Two buttons should appear when it works.

import java.awt.Color;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;

public class PanelTest {
public static void main(String[] args) {
    JFrame frame = new JFrame();
    JPanel mainPanel = new JPanel();
    JPanel panel1 = new JPanel();
    JPanel panel2 = new JPanel();

    JLayeredPane layers = new JLayeredPane();
    mainPanel.add(layers);

    panel2.setOpaque(false);
    panel1.setOpaque(false);
    panel1.setVisible(true);
    panel2.setVisible(true);

    panel1.add(new JButton("1111111111"));
    panel2.add(new JButton("2"));

    frame.setContentPane(mainPanel);
    layers.add(panel1, new Integer(2));
    layers.add(panel2, new Integer(3));

    frame.setVisible(true);
    frame.setSize(500, 500);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

Only the grey background of the mainPanel is visible. What am I doing wrong?


Solution

  • When adding a component to a JLayeredPane, you're essentially adding the component to a null layout using container. This means that you must fully specify both the component's size and its position, often solving both with a setBounds(...) call. Call this on panel1 and panel2, for example:

    panel1.setBounds(10, 10, 100, 100);
    panel2.setBounds(70, 70, 100, 100);
    

    Edit:

    setting bounds didn't make any difference

    Setting the size (bounds) is required but you still have an additional problem.

    You are adding the JLayeredPane to a JPanel which uses a FlowLayout. By default a FlowLayout respects the preferred size of the component added to it. Since JLayeredPane uses a null layout its preferred size is (0, 0) so there is nothing to paint.

    Two solutions:

    1. You don't need the JPanel, just use: frame.setContentPane(layers);
    2. If you really want to use the panel then you need to change the layout manager: JPanel mainPanel = new JPanel( new BorderLayout());