I'm currently trying to make a game with a menu. Menu looks like this. http://puu.sh/xGoC
Ideally, when I push a button, it will bring me to the game. The game looks like this. http://puu.sh/xGoV
I currently initialize a JFrame() in my main class which runs either the menu class or the game class (Both of which are JPanels).
How would I go about using CardLayout to make it so that I can initialize the game menu and when I click a button, change the panel to the game panel?
Don't use
CardLayout
for that.Instead, remove the menu panel from the frame's content pane and add the game panel.
Remember to
validate()
the frame as well. Something like this:In the program that I'm currently working on I have a class called ViewManager that creates static instances of each view and adds them to an array with indices that correspond to the constant fields. I also have fields to keep track of previous views for breadcrumbs / going back. It might be a case of re-inventing the wheel, but it allows you to control everything about it. And it's efficient.
I've got some sample code for you, it's not perfect, but it should work. Basically, you want to use the NEXT or PREVIOUS calls on the layout manager.
As there's only two panels, I just use the NEXT call to cycle through them. It's probably the best if you read the Swing documentation though, this works, but you might have other requirements as well.