0

I'm trying to program a game that has a title screen, and when you press Enter it advances to the game. The issue that I'm running into is that you can't put add a JPanel from a KeyPressed method.

I have one panel for the title and another for the game board, what is likely the best way to go about this?

Roman C
  • 49,761
  • 33
  • 66
  • 176
Christian Baker
  • 375
  • 2
  • 7
  • 22
  • Take a look at http://stackoverflow.com/questions/15599748/jpanel-keylistener-not-working – Ross Drew Nov 26 '13 at 15:56
  • The code won't even compile with an add method in the KeyPressed method. Making the panel focusable so it will register key presses isn't the issue. – Christian Baker Nov 26 '13 at 16:04

2 Answers2

2

I have one panel for the title and another for the game board, what is likely the best way to go about this?

Use a Card Layout so you can easily switch from the title panel to the game panel.

Your title panel should also probably have a button like "Start Game" so the user knows what to do. Then they can either click the button or press Enter.

and when you press Enter it advances to the game

To make the button the default button (so it responds to Enter) for the panel you can use:

frame.getRootPane().setDefaultButton(gameButton);

If you don't like the idea of adding a button then you will need to use Key Bindings.

camickr
  • 321,443
  • 19
  • 166
  • 288
1

You might want to take a look at CardLayout.

Kevin Workman
  • 41,537
  • 9
  • 68
  • 107