Search code examples
javaswinguser-interfacelayout-managercardlayout

Multiple jPanels in a jFrame and switching the jPanels out


right now I´m trying to programm a little Tetris clone. Therefore I want to have ONE jFrame, which should contain multiple jPanels (for the Main Menu, the game itself, Options, etc etc...).

I searched a bit and a lot of people say that one should use a CardLayout. So I went to my NetBeans GUI Builder, made a jFrame switched it to CradLayout and added 2 Panels; the first panel only contains a button, and the second panel contains my "game" (my graphical display of my Tetrismatrix, the graphical display of the next Block, and a exit button).

Pictures for better understanding:

The "Main Menu" is only a button that says "Start game" (can´t post more than 2 links because I´m new).

My current "Game Menu"

The structure of the "Card Layout in the NetBeans GUI Builder"

To achieve the switch between the Panels I´m using this (found after a little research):

@Action
public void cardSwitcher() {
    CardLayout cl = (CardLayout) (gamePanel.getLayout());
    cl.next(gamePanel);
}

Pressing the "Start Game" button then calls the method cardSwitcher().

When I now run my jFrame it starts just fine, I see my Start Game button and everything. But as soon as I press the button I get an ClassCastException.

"javax.swing.GroupLayout cannot be cast to java.awt.CardLayout"

So now my question is, can I even achieve my goal to have 1 Frame with multiple jPanels in it switching these with the CardLayout or is there a easier/better way to do this?

Thanks in advance for any help.

PS: I´m sorry for wrong spelling or bad grammar, I´m not a native speaker. In addition if the question is already answered and I was to dumb to find the Post about it I´m going to remove this post immediately. And I´m always open for constructive critic.


Solution

  • Yes you can switch panels in cardLayout. You should take the cardLayout directly from the component on which you defined it (probably JFrame#getLayout()) not from panel inside the cardLayout (from what you've written I assume that gamePanel is inside cardLayout).