Petros17
Petros17

Reputation: 40

Card Layout Panel showing wrong panel - Java Swing

I want INIT_PANEL to be on top at first, and then (later) a button click will switch it to GAME_PANEL. But, GAME_PANEL is the top one when I run it...

What am I doing wrong?

Here's the important part of code:

public class MainFrame extends JFrame {

private JPanel contentPane;
private static final String GAME_PANEL = "Game panel";
private static final String INIT_PANEL = "Initial panel";

private void addPanels(){
    contentPane.add(new GamePanel(), GAME_PANEL);
    contentPane.add(new InitialPanel(this), INIT_PANEL);
    ((CardLayout) contentPane.getLayout()).show(contentPane, INIT_PANEL);
}

void switchPanels(){
    ((CardLayout) contentPane.getLayout()).next(contentPane);
}


public MainFrame(){
    ////////////////////////////resizing

    contentPane = new JPanel();
    contentPane.setLayout(new CardLayout(20,20));

    addPanels();

    ////////////////////////listener for closing
}
}

Upvotes: 0

Views: 90

Answers (1)

Agricola
Agricola

Reputation: 602

I don't thin the problem you are experiencing is in the code provided. The one thing I had to change to get this working is add the content pane, which was never added:

public MainFrame(){
    ////////////////////////////resizing

    contentPane = new JPanel();
    contentPane.setLayout(new CardLayout(20,20));

    addPanels();

    this.add(this.contentPane); // I added this

    ////////////////////////listener for closing
}

At that point it was just working. So my guess is if this is something cut right from you code, you didn't add the content pane and what you are thinking is the game panel is actually being rendered somewhere else. Is that assumption correct?

Upvotes: 1

Related Questions