【问题标题】:Java CardLayout not displayingJava CardLayout 不显示
【发布时间】:2014-06-03 05:53:15
【问题描述】:

我有一个已经运行并可以运行的游戏,我想为它添加一个标题屏幕。我正在尝试添加一个 CardLayout 以便在游戏和标题屏幕之间轻松切换。我目前的问题是没有显示任何内容。这是一张图片:http://i.imgur.com/kVIXYQ7.png。当我运行它时,我只是得到一个空白的 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);}
}

【问题讨论】:

  • 感谢@MadProgrammer,现在一切正常。我开始我的标题屏幕,然后转到游戏。唯一的问题是我的游戏没有注册键,但这可能是因为我的标题屏幕使用了键监听器。不确定我是否应该尝试在此处修复此错误或提出新问题。

标签: java swing layout-manager cardlayout


【解决方案1】:

您尚未将Cards 添加到任何内容。

尝试将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);

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

【讨论】:

  • 请不要在评论中发布代码或堆栈跟踪。在问题中更容易阅读。至于这个问题,NPE 是一个单独的问题,与“卡片没有变化”有关。
  • 听起来您的某个类尝试加载图像时遇到问题,上述问题中没有显示
猜你喜欢
  • 1970-01-01
  • 2023-03-28
  • 2012-11-05
  • 1970-01-01
  • 2013-04-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多