2017-10-22 197 views
1

所以,我试图为一个简单的游戏制作一个基本的功能菜单。我试图通过创建2个JPanels,一个用于实际游戏,另一个用于我的菜单来实现。如何在面板内切换JFrame中的JPanel?

我想要做的是在我的菜单面板上有一个按钮,当按下时,将JPanel从菜单的JFrame中显示到实际游戏的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

'更好的方式来来回切换菜单和游戏之间的' - 使用[卡布局(https://docs.oracle.com/javase/tutorial /uiswing/layout/card.html),用于在同一个容器中交换面板。 – camickr

+1

不要承担容器层次结构。使用观察者模式,并从小组发送通知给观察员,他能够更好地确定应该完成的工作 – MadProgrammer

回答

2

像这样:

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(); 
    } 
} 
+0

我认为这个(被删除的评论)需要另一个问题/帖子,最好用[mcve]。 'JPanels'不必与父母在同一个班上。共享属性有许多选择,包括getter和setter。 – c0der

+0

我删除了评论,因为我意识到这很愚蠢......但有一件事,如果我想要在主菜单上的按钮切换到其他窗格,并从另一个窗口切换回主菜单,我将如何使用卡片布局事件发生时的窗格? (例如,你在游戏中死亡)意思是,没有按钮总是在那里 –

+0

'我将如何使用卡片布局... - - 这就是为什么你阅读你给的教程链接。然后,当您遇到问题时,您可以尝试发布帖子和发布代码。努力工作,不要指望人们为你提供喂食代码。 – camickr