I have a game that already runs and works and I want to add a title screen to it. I'm trying to add a CardLayout for easy switching between game and titlescreen. My current issue is that nothing is being displayed. Here is an image: http://i.imgur.com/kVIXYQ7.png . I simply get a blank JPanel when I run it. What am I doing wrong?
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);}
}
You haven't added Cards
to anything.
Try adding Cards
to frame and then make the frame visible
For example...
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);
FYI: You should come setResizable
before setting the frame size as setResizable
can change the frames border insets
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.