试图在 JLayeredPane 中重叠两个相同大小的 JPanel

Trying to overlap two same size JPanels in a JLayeredPane

我试图重叠两个相同大小的 JPanel(此处 'pseudo' 和“svg”)。 JPanel pseudo 在 svg 后面。 JButton 应该在 svg 前面伪移动。结果是centerPanel.moveToFront(伪)不起作用。我错过了什么吗?

        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);
            }
        });

The JButton is supposed to move pseudo in front of svg

那么你应该使用 CardLayoutCardLayout 是一种布局管理器,它让 2 个(或更多)组件占用相同的 space,但一次只有一个组件可见。

阅读有关 How to Use CardLayout 的 Swing 教程部分,了解更多信息和入门示例

新代码是:

        JPanel cardsPanel = new JPanel(new CardLayout());

        cardsPanel.add(svg, "svgPanel");
        cardsPanel.add(pseudo, "pseudo");

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

        view3D.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                    CardLayout cl = (CardLayout)(cardsPanel.getLayout());
                    cl.show(cardsPanel, "pseudo");
                }
            }
        });