javaswingjpaneljlayer

JPanel on top of another JPanel


I have been using JPanels for a while and now want to place a JPanel on top of another JPanel.

I have looked at using JLayer but I was wondering If there is a solution to just set the layer of the bottom and top, I don't want to set each components layer if possible.

Example

JPanel bottomPanel = new JPanel();      # Set as bottom panel
JPanel topPanel = new JPanel();         # Set as top panel
JPanel sidePanel = new JPanel();        # Don't have to set
JPanel anotherSidePanel = new JPanel(); # Don't have to set

If this isn't possible what is the best solution for this, Thanks.


Solution

  • You can have the main panel use a BorderLayout.

    Then you can do something like:

    mainPanel.add(leftSide, BorderLayout.LINE_START);
    mainPanel.add(rightSide, BorderLayout.LINE_END);
    JLayeredPane lp = new JLayeredPane();
    mainPanel.add(lp, BorderLayout.CENTER);