2015-05-01 53 views
0

希望你們都能幫助我理解這個謎團。我創建了一個包含「返回」按鈕的JPanel,並且有一個我喜歡的漂亮佈局。我想添加這個JPanel(我將從此處稱爲homeButtonPanel)到其他幾個JPanel,因爲我希望他們都有一個「返回」按鈕。JPanel在添加到多個其他JPanel時消失

我將homeButtonPanel添加到JPanel gameRoom,然後添加到JPanel gamePlay。當gameRoom顯示在主JFrame中時,homeButtonPanel未顯示。當在主JFrame中顯示gamePlay時,顯示HomeButtonPanel 。我無法弄清楚這麼久。

這麼多混亂和挫折,我意識到,當我註釋掉所添加的homeButtonPanel到遊戲面板的線,homeButtonPanel將所述gameRoom面板上顯示。

爲什麼我不能將這個JPanel添加到多個額外的JPanel?

(亦作參考我使用CardLayout到顯示JPanels之間切換,如果該事項)

 //Set up of the GameRoom Panel 
     //********************************************************************** 
     JPanel gameRoom = new JPanel(); 

     //create welcome label 
     JLabel welcomeGameRoom = new JLabel("Welcome to the GameRoom"); 

     //create the go home button (and its panel) 
     JPanel homeButtonHolder= new JPanel(); 
     JButton goHome = new JButton("Go Home"); 
     goHome.setVisible(true); 
     homeButtonHolder.add(goHome); 

     //add the go home holder to the gameplay panel 
     gameRoom.add(homeButtonHolder); 

     //add the welcome label to the gameplay panel 
     gameRoom.add(welcomeGameRoom); 

     //add the gameroom panel to the card panel 


     //Set up of the GamePlay Panel 
     //********************************************************************** 
     JPanel gamePlay = new JPanel(); 
     JLabel welcomeGamePlay = new JLabel("Welcome to the Game"); 

     //add the go home holder to the gameplay panel 
     //*****This is the line that is the issue *************** 
     gamePlay.add(homeButtonHolder); 

     //add the welcome label to the gameplay panel 
     gamePlay.add(welcomeGamePlay); 
+0

After [link](http://docs.oracle.com/javase/tutorial/uiswing/components/toplevel.html):「每個GUI組件只能包含一次,如果一個組件已經在一個容器中並且您嘗試將其添加到另一個容器,該組件將從第一個容器中移除,然後添加到第二個「 –

回答

1

我添加homeButtonPanel到的JPanel gameRoom,然後到JPanel的遊戲。

組件只能有一個父組件,所以不能將同一個組件添加到多個面板。

因此,您需要創建兩個「homeButtonPanel」實例,然後將實例添加到每個面板。

另一種選擇是讓您的主面板使用BorderLayout。然後使用CardLayout將面板添加到BorderLayout的中心。然後,可以將「homeButtonPane」添加到此面板的PAGE_END中,所以現在即使交換面板,HomeButtonPanel也會屬於CardLayout中的兩個面板。

+0

謝謝! @camickr我沒有意識到一個組件只能有一個父代。 –