Search code examples
javaswingpong

How to Use A CardLayout in My Situation


I have not been able to find a way to use a CardLayout that works.

I am creating a Pong game. I have a class that extends a JFrame and two classes that extend a JPanel. I am trying to make it so that when the method gets fired in the the first JPanel, it switches from the first JPanel to the second JPanel.

How would I do this, and please provide code.


Solution

  • What you do is use a CardLayout on the parent component that will hold your two JPanels. When you add the JPanels to the parent component, you'll need to provide a String for each one, which will be used later to switch between the cards.

    CardLayout cardLayout = new CardLayout();
    JPanel parentComponent = new JPanel(cardLayout);
    parentComponent.add( jPanel1, "Panel 1" );
    parentComponent.add( jPanel2, "Panel 2" );
    

    Then when you want to switch the cards, you need to call a method on the CardLayout layout manager, so you'll need to get it from the parent component and cast it, or just save a reference to it when you create your parent component. Now to switch the cards:

    cardLayout.show( parentComponent, "Panel 1" ); // Shows panel 1
    cardLayout.show( parentComponent, "Panel 2" ); // Shows panel 2