简体   繁体   English

卡布局面板显示错误的面板-Java Swing

[英]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. 我希望INIT_PANEL首先位于顶部,然后(稍后)单击按钮将其切换为GAME_PANEL。 But, GAME_PANEL is the top one when I run it... 但是,当我运行GAME_PANEL时,它是排名第一的...

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? 这个假设正确吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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