Switching between JPanels

后端 未结 3 1172
梦谈多话
梦谈多话 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.

    0 讨论(0)
  • 2021-01-21 02:40

    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)

    0 讨论(0)
  • 2021-01-21 02:52

    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.

    0 讨论(0)
提交回复
热议问题