title: How to build a java Main Menu
body: <p>Obviously I am trying to make a main menu using the swing components. I understand that in order to make my menu happen, I have to utilize <code>CardLayout</code>, which I do in the code below:</p>
  
  <p>(Everything is imported of course)</p>
  
  <pre><code> public class Screen extends JFrame implements ActionListener {
  private static final long serialVersionUID = 1L;
  
  int width, height;
  
  JButton play = new JButton("play");
  JButton settings = new JButton("settings");
  JButton exit = new JButton("exit");
  JButton mainMenu = new JButton("main menu");
  
  CardLayout layout = new CardLayout();
  
  JPanel panel = new JPanel();
  JPanel game = new JPanel();
  JPanel menu = new JPanel(); 
  
  public Screen(int width, int height) {
      this.width = width;
      this.height = height;
  
      panel.setLayout(layout);        
      addButtons();
  
      setSize(width, height);
      setResizable(false);
      setLocationRelativeTo(null);
      setVisible(true);
      setTitle("BUILD YOUR EMPIRE");
      setDefaultCloseOperation(EXIT_ON_CLOSE);
      requestFocus();
  
  }
  
  private void addButtons() {
  
      play.addActionListener(this);
      settings.addActionListener(this);
      exit.addActionListener(this);
      mainMenu.addActionListener(this);
  
      //menu buttons
      menu.add(play);
      menu.add(settings);
      menu.add(exit);
  
      //game buttons
      game.add(mainMenu);
  
      //background colors
      game.setBackground(Color.MAGENTA);
      menu.setBackground(Color.GREEN);
  
      //adding children to parent Panel
      panel.add(menu,"Menu");
      panel.add(game,"Game");
  
      add(panel);
      layout.show(panel,"Menu");
  
  }
  
  public void actionPerformed(ActionEvent event) {
  
      Object source = event.getSource();
  
      if (source == exit) {
          System.exit(0);
      } else if (source == play) {
          layout.show(panel, "Game");
      } else if (source == settings){
  
      } else if (source == mainMenu){
          layout.show(panel, "Menu");
      }
  
      }
  }
  </code></pre>
  
  <p>But when I run it, only the exit button works.
  When I hit the settings button nothing happens (as expected)
  but when I hit play button it crashes and gives me this error:</p>
  
  <pre><code> Exception in thread "main" java.lang.IllegalArgumentException: wrong parent for CardLayout
  at java.awt.CardLayout.checkLayout(Unknown Source)
  at java.awt.CardLayout.show(Unknown Source)
  at Screen.Buttons(Screen.java:69)
  at Screen.&lt;init&gt;(Screen.java:31)
  at Window.main(Window.java:29)
  </code></pre>
  
  <p>I dont understand what I am doing wrong.
  Any help on this will be greately appreciated thanks in advance.</p>