希望你們都能幫助我理解這個謎團。我創建了一個包含「返回」按鈕的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);
After [link](http://docs.oracle.com/javase/tutorial/uiswing/components/toplevel.html):「每個GUI組件只能包含一次,如果一個組件已經在一個容器中並且您嘗試將其添加到另一個容器,該組件將從第一個容器中移除,然後添加到第二個「 –