Search code examples
javaswingjlayeredpane

Trying to overlap two same size JPanels in a JLayeredPane


I am trying to overlap two same size JPanels (here 'pseudo' and ' svg'). JPanel pseudo is behind svg. The JButton is supposed to move pseudo in front of svg. The result is that centerPanel.moveToFront(pseudo) does not work. Did I miss something?

        centerPanel = new JLayeredPane();
        centerPanel.setLayout(new BorderLayout());

        centerPanel.add(pseudo, BorderLayout.CENTER, -1);
        centerPanel.add(svg, BorderLayout.CENTER, 0);

        view3D = new JButton("View 3D");

        view3D.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                centerPanel.moveToFront(pseudo);
            }
        });

Solution

  • The JButton is supposed to move pseudo in front of svg

    Then you should be using a CardLayout. A CardLayout is a layout manager that lets 2 (or more) components occupy the same space, but only one component is visible at a time.

    Read the section from the Swing tutorial on How to Use CardLayout for more information and a working example to get you started