Sign in to follow this  

JPanel switching? Please help a newbie...

This topic is 2155 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hello! I need help in trying to switch JPanels in one JFrame. So far my game has two JPanels. One(MainMenu) is the main menu and the other is the actual game(GameFrame). I would like it so that when I push the ENTER key from the main menu, it removes the MainMenu panel and switch it to the GameFrame panel. I am suppose to use a CardLayout but I have not found any tutorial that I understand. Any help would be appreciated. Thank you!

Share this post


Link to post
Share on other sites
You need 3 JPanels.

1 that uses the card layout
1 for your main menu
1 for your game

Add the JPanels for the menu and for the game to the jpanel that uses the cardlayout , pass an identifying string along with them.
mainPanel = new JPanel(new CardLayout());
mainPanel.add(gamePanel,"GamePanel");
mainPanel.add(menuPanel,"MenuPanel");

When you wish to change the visible JPanel you grab the layout from the main panel (The one that uses the card layout) using:
CardLayout layout = (CardLayout)(mainPanel.getLayout());
and then change the visible panel using
layout.show("GamePanel");
or
layout.show("MenuPanel");

Share this post


Link to post
Share on other sites
Sign in to follow this