我正在制作一款使用CardLayout在四个JPanel(gamePanel,startMenu,pauseMenu和levelMenu)之间切换的游戏。我得到了异常" java.lang.IllegalArgumentException:CardLayout错误的父级"。但是,我将所有卡添加到面板,其中有布局管理器CardLayout,所以我不明白为什么面板不能成为父面板。我已经查看了CardLayout的Java教程以及涉及IllegalArgumentException的Stack Overflow问题,但是我无法看到我做错了什么。提前谢谢。
游戏:
import java.awt.CardLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
/** Class Contains the main method and the game's logic */
public class Game {
/** Field The JFrame for the game */
public JFrame frame = new JFrame();
/** Field The JPanel that uses CardLayout to only display one JPanel at a time */
private JPanel panel;
/** Field The CardLayout that controls which JPanel is showing */
private CardLayout cardLayout;
/** Field The JPanel that displays the playing field */
private JPanel gamePanel = new JPanel();
/** Field The first menu the player sees */
private JPanel startMenu = new JPanel();
/** Field The menu the player sees when the game is paused */
private JPanel pauseMenu = new JPanel();
/** Field The menu that allows the player to select which level to play */
private JPanel levelMenu = new JPanel();
/** Constructor for Game with no parameters */
public Game() {
initializeGame();
}
/** Main method of Game */
public static void main(String argv[]) {
new Game();
}
/** Sets up frame and panel */
private void initializeGame() {
panel = createPanel();
panel = (JPanel) frame.getContentPane();
cardLayout.show(panel, "startMenu");
}
private JPanel createPanel() {
panel = new JPanel();
cardLayout = new CardLayout();
panel.setLayout(cardLayout);
panel.add(startMenu, "startMenu");
panel.add(pauseMenu, "pauseMenu");
panel.add(levelMenu, "levelMenu");
panel.add(gamePanel, "gamePanel");
return panel;
}
}
答案 0 :(得分:2)
您已将panel
变量分配给两个对象,一个是createPanel()
方法创建的,另一个是通过获取contentPane。一个是你用GUI添加组件,另一个是你打开show方法,因此JVM抱怨。解决方案不是这样做,只为此变量分配一次对象。
要了解我的意思,请搜索您的代码
panel =
并查看弹出的行。