有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

swing Java 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);}
}

共 (1) 个答案

  1. # 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可以更改帧边框插入