I'm trying to make a game. There's several different screens in the game such as a main menu, and the actual game screen. Each of these is a separate jpanel extension. I have added each of them to my JFrame which is a class called Game. In my game class I have the following methods
public void addPanel( JPanel p ) {
panels.add( p ); // An array of all the different panels I need
this.getContentPane().add( p );
}
public void switchToPanel( JPanel p ) {
for ( JPanel somePanel : panels ) {
somePanel.setVisible( false );
}
p.setVisible( true );
repaint();
}
The point of this is that I have many different panels and when I need to show a particular one, such as a menu screen, I call switchToPanel( myPanel ). Basically just hiding every panel and then unhiding the one that I need to see. Only problem is that these panels aren't showing up when I switch to them. The only one that will ever show up is the panel that I added last. In Objective C I use this technique for switching between views all the time and I've never had any problems. Is this kind of thing not allowed in java?
Edit: now I am calling repaint() after switching, but it's still not working
You can do a number of different things to achieve the same effect.
The first suggestion I'd make is use CardLayout (How to Use CardLayout) as this is what it was designed to do.
The other would be to use a JTabbedPane (How to use Tabbed Panes)