如何在面板中切换JFrame中的JPanel?

时间:2017-10-22 02:43:15

标签: java swing menu jframe jpanel

所以,我正在尝试为简单的游戏制作一个基本的功能菜单。我尝试通过创建2个JPanel来实现这一点,一个用于实际游戏,另一个用于我的菜单。

我要做的是在我的菜单面板上有一个按钮,当按下该按钮时,将在父JFrame中显示的JPanel从菜单的显示切换到实际游戏的JPanel。

这是我的代码:

class Menu extends JPanel
{
   public Menu()
   {
      JButton startButton = new JButton("Start!");
      startButton.addActionListener(new Listener());
      add(startButton);
   }

   private class Listener implements ActionListener
   {
      public void actionPerformed(ActionEvent e)
      {     
         Container container = getParent();
         Container previous = container;
         System.out.println(getParent());
         while (container != null)
         {
            previous = container;
            container = container.getParent();
         }
         previous.setContentPane(new GamePanel());      
      }
   }
}

如您所见,我为我的开始按钮创建了一个监听器。在监听器内部,我使用while循环通过getParent()方法访问JFrame。该程序正在获取JFrame对象,但它不允许我调用setContentPane方法...

有谁知道如何让这个工作,或者更好的方式在菜单和游戏之间来回切换?

1 个答案:

答案 0 :(得分:3)

像这样:

public class CardLayoutDemo extends JFrame {

    public final String YELLOW_PAGE = "yellow page";
    public final String RED_PAGE = "red page";
    private CardLayout cLayout;
    private JPanel mainPane;
    boolean isRedPaneVisible;

    public CardLayoutDemo(){

        setTitle("Card Layout Demo");
        setSize(400,250);
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        mainPane = new JPanel();
        cLayout = new CardLayout();
        mainPane.setLayout(cLayout);

        JPanel yellowPane = new JPanel();
        yellowPane.setBackground(Color.YELLOW);
        JPanel redPane = new JPanel();
        redPane.setBackground(Color.RED);

        mainPane.add(YELLOW_PAGE, yellowPane);
        mainPane.add(RED_PAGE, redPane);
        showRedPane();

        JButton button = new JButton("Switch Panes");
        button.addActionListener(e -> switchPanes() );

        setLayout(new BorderLayout());
        add(mainPane,BorderLayout.CENTER);
        add(button,BorderLayout.SOUTH);
        setVisible(true);
    }

    void switchPanes() {

        if (isRedPaneVisible) {showYelloPane();}
        else { showRedPane();}
    }

    void showRedPane() {
        cLayout.show(mainPane, RED_PAGE);
        isRedPaneVisible = true;
    }

    void showYelloPane() {
        cLayout.show(mainPane, YELLOW_PAGE);
        isRedPaneVisible = false;
    }

    public static void main(String[] args) {
        new CardLayoutDemo();
    }
}