简体   繁体   中英

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
}
}

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM