Switching between JPanels

后端 未结 3 1171
梦谈多话
梦谈多话 2021-01-21 01:58

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

3条回答
  •  温柔的废话
    2021-01-21 02:29

    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.

提交回复
热议问题