How can I switch between jpanels?

后端 未结 3 942
独厮守ぢ
独厮守ぢ 2020-12-11 21:28

I\'m still very new to java programming, so please help me to correct any mistakes I might have overlooked or give tips on how to improve this program.

Okay, so a lo

3条回答
  •  情书的邮戳
    2020-12-11 21:55

    "Is there a way for me to add my GameMenu jpanel to my jframe, and then replace it with the Pipes jpanel?"

    As other have suggested, for this you want a CardLayout. It is very simple to you. Personally, I always wrap my CardLayout in a JPanel rather than the JFrame, just force of habit.

    What you want to do is have a mainPanel that will have the CardLayout

    CardLayout card = new CardLayout();
    JPanel mainPanel = new JPanel();
    

    Then you want to add your panels to the mainPanel. What the CardLyaout does is layer the panels, making just one visible at a time. The first one you add, will the in the foreground. Also when you add the panel, you'll also want to issue it a key it can be called from. The key, can be any String you like.

    mainPanel.add(gameMenu, "menu");
    mainPnael.add(pipes, "pipe");
    

    Now gameMenu is the only panel shown. To show pipes, all you do is use this method

    • public void show(Container parent, String name) - Flips to the parent that was added to this layout with the specified name, using addLayoutComponent. If no such component exists, then nothing happens.

    So you'd use, card.show(mainPanel, "pipes");

    Whatever even you want to trigger the showing of pipes, just add that line in that event handler. You could add a button or something to the GameMenu that will allow movement to the Pipes panel.

提交回复
热议问题