Java CardLayout未显示

Java CardLayout未显示,java,swing,layout-manager,cardlayout,Java,Swing,Layout Manager,Cardlayout,我有一个游戏,已经运行和工作,我想添加一个标题屏幕到它。我正在尝试添加一个卡片布局,以便在游戏和标题屏幕之间轻松切换。我当前的问题是没有显示任何内容。这是一张图片:。我只是在运行它时得到一个空白的JPanel。我做错了什么 public class UI { private static JPanel cards; private static CardLayout cardLayout; public static void main(String args[]) {new UI()

我有一个游戏,已经运行和工作,我想添加一个标题屏幕到它。我正在尝试添加一个卡片布局,以便在游戏和标题屏幕之间轻松切换。我当前的问题是没有显示任何内容。这是一张图片:。我只是在运行它时得到一个空白的JPanel。我做错了什么

public class UI
{
private static JPanel cards;
private static CardLayout cardLayout;

public static void main(String args[])
    {new UI();}

public UI()
{
    JFrame frame = new JFrame("Scrolling Shooter");

    frame.setResizable(false);
    Toolkit tk = Toolkit.getDefaultToolkit();  
    int width = ((int) tk.getScreenSize().getWidth());  
    int height = ((int) tk.getScreenSize().getHeight());  
    frame.setSize(width, height);

    TitleScreen title = new TitleScreen(frame);
    ScrollingShooter game = new ScrollingShooter(frame);

    cards = new JPanel(new CardLayout());
    cards.add(title, "title");
    cards.add(game, "game");
    cards.setOpaque(true);
    frame.getContentPane().add(cards);

    cardLayout = (CardLayout) cards.getLayout();
    cardLayout.first(cards);

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
}

/**
 * Switches to the next screen
 */
public static void nextScreen()
    {cardLayout.next(cards);}

/**
 * Returns to the first screen
 */
public static void firstScreen()
    {cardLayout.first(cards);}
}

您没有向任何内容添加

尝试将
卡添加到框架中,然后使框架可见

例如

JFrame frame = new JFrame("Scrolling Shooter");

TitleScreen title = new TitleScreen(frame);
ScrollingShooter game = new ScrollingShooter(frame);

cards = new JPanel(new CardLayout());
cards.add(title, "title");
cards.add(game, "game");
cards.setOpaque(true);

cardLayout = (CardLayout) cards.getLayout();
cardLayout.first(cards);

frame.add(cards);
//...
frame.setResizable(false);
frame.setSize(width, height);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);

仅供参考:在将帧大小设置为
setresizeable
之前,您应该先来
setresizeable
可以更改帧边框插图

请不要在注释中发布代码或堆栈跟踪。它在一个问题中更容易理解。至于这个问题,NPE是一个与“卡片无变化”相关的单独问题。听起来你的一个同学在尝试加载图像时遇到了问题,这在上面的问题中没有显示出来,这要感谢@MadProgrammer,因为它现在都在工作。我启动标题屏幕,然后进入游戏。唯一的问题是我的游戏没有注册密钥,但这可能是因为我的标题屏幕使用了密钥侦听器。不确定我是否应该尝试在这里修复此错误或提出新问题。