如何在面板中切换JFrame中的JPanel?

所以,我正在尝试为简单的游戏制作一个基本的function菜单。 我尝试通过创建2个JPanels来实现这一点,一个用于实际游戏,另一个用于我的菜单。

我要做的是在我的菜单面板上有一个按钮,当按下时,将在父JFrame中显示的JPanel从菜单的显示切换到实际游戏的JPanel。

这是我的代码:

class Menu extends JPanel { public Menu() { JButton startButton = new JButton("Start!"); startButton.addActionListener(new Listener()); add(startButton); } private class Listener implements ActionListener { public void actionPerformed(ActionEvent e) { Container container = getParent(); Container previous = container; System.out.println(getParent()); while (container != null) { previous = container; container = container.getParent(); } previous.setContentPane(new GamePanel()); } } } 

如您所见,我为我的开始按钮创建了一个Listener。 在侦听器内部,我使用while循环通过getParent()方法到达JFrame。 程序正在获取JFrame对象,但它不会让我调用setContentPane方法…

有谁知道如何使这个工作,或更好的方式来切换菜单和游戏之间的来回?

像这样:

 public class CardLayoutDemo extends JFrame { public final String YELLOW_PAGE = "yellow page"; public final String RED_PAGE = "red page"; private CardLayout cLayout; private JPanel mainPane; boolean isRedPaneVisible; public CardLayoutDemo(){ setTitle("Card Layout Demo"); setSize(400,250); setDefaultCloseOperation(EXIT_ON_CLOSE); mainPane = new JPanel(); cLayout = new CardLayout(); mainPane.setLayout(cLayout); JPanel yellowPane = new JPanel(); yellowPane.setBackground(Color.YELLOW); JPanel redPane = new JPanel(); redPane.setBackground(Color.RED); mainPane.add(YELLOW_PAGE, yellowPane); mainPane.add(RED_PAGE, redPane); showRedPane(); JButton button = new JButton("Switch Panes"); button.addActionListener(e -> switchPanes() ); setLayout(new BorderLayout()); add(mainPane,BorderLayout.CENTER); add(button,BorderLayout.SOUTH); setVisible(true); } void switchPanes() { if (isRedPaneVisible) {showYelloPane();} else { showRedPane();} } void showRedPane() { cLayout.show(mainPane, RED_PAGE); isRedPaneVisible = true; } void showYelloPane() { cLayout.show(mainPane, YELLOW_PAGE); isRedPaneVisible = false; } public static void main(String[] args) { new CardLayoutDemo(); } }