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
If you are making a game, you make it in a separate thread different from the EDT
. Most games show different screens by not changing panels but they use a single panel, on which they render according to GameState
.
Here's an example.
public class MyGame extends JPanel implements Runnable {
public static enum GameState {
MENU, INTRO, LEVELS, END, TITLES
}
GameState state = GameState.MENU;
public MyGame(){
setDoubleBuffered(true);
// Initialize the resources
new Thread(this).start();
}
public void update(long elapsedTime){
switch (state){
case MENU:
// Show the menu
break;
....
}
}
private void GameLoop(){
// Game Loop goes here
}
public void run(){
GameLoop();
}
public void paint(Graphics g){
// switch and draw your game
}
public static void main(String[] args){
JFrame f = new JFrame("MyGame");
f.setSize(640, 480);
f.add(new MyGame());
f.setVisible(true);
}
}
If one state ie., a menu completed, change the state
variable. And first learn using a GameEngine
before you make it on your own.
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)
If you want to switch between two panels add those panels into another JPanel and use cardLayout. Then, before adding a JPanel
remove the current one. Like this:
parentPanel.removeAll();
parentPanel.repaint();
parentPanel.revalidate();
parentPanel.add(childPanel1);
parentPanel.repaint();
parentPanel.revalidate();
Likewise do the same thing for other child panels.