为什么我的CardLayout给“ CardLayout的父代错误”?

时间:2018-10-28 01:01:44

标签: java swing user-interface awt cardlayout

当我运行此代码时,它给我“ CardLayout的父代错误”。我对错误在哪里感到困惑。该代码的目的是在按下playButton时在同一帧上访问新的纸牌布局。对于CardLayout的工作方式,我还不太了解,但是我仍然停留在这一点上。有关如何解决此问题以及实际错误是什么的建议将不胜感激。请查找CardLayout,panel,panel2,setLayout等。

//imports omitted

public class Menu extends JFrame {

public Menu() {

新CardLayout实例

    //CardLayout instances
    CardLayout menuLayout = new CardLayout();

    //JFrame instances
    JFrame frame = new JFrame("PrimeTime Game");

    //JPanel instances
    JPanel panel = new JPanel();
    JPanel panel2 = new JPanel();

    menuLayout.show(panel, "1");

    //Button instances
    JButton playButton = new JButton("Play");
    JButton highScoreButton = new JButton("Highscores");
    JButton exitButton = new JButton("Exit game");
    JButton startButton = new JButton("Start");

    //JFrame INSTANCE: frame
    frame.add(panel);
    frame.add(panel2);
    frame.setVisible(true);
    frame.setSize(490, 600);

将menyLayout添加到面板

    //JPanel INSTANCE: panel
    panel.add(playButton);
    panel.add(highScoreButton);
    panel.add(exitButton);
    panel.setLayout(menuLayout);

将menuLayout添加到panel2

    //JPanel INSTANCE: panel2
    panel2.add(startButton);
    panel2.setLayout(menuLayout);

    //JButton INSTANCE: playButton
    playButton.setSize(200, 300);

actionPerformed方法

    playButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            menuLayout.show(panel2, "2");
        }
    });

    //JButton INSTANCE: highScoreButton
    highScoreButton.setSize(200, 300);

    //JButton INSTANCE: exitButton
    exitButton.setSize(200, 300);

    //JButton INSTANCE: startButton
    startButton.setSize(200, 300);
}

}

0 个答案:

没有答案