Reputation: 15
Hopefully you all can help me understand this mystery. I created a JPanel that contained a "Go Back" button and had a nice layout that I liked. I wanted to add this JPanel (I'll call it homeButtonPanel from here on out) to several other JPanels because I want them all to have a "Go Back" button.
I added homeButtonPanel to JPanel gameRoom, and then to JPanel gamePlay. When gameRoom was shown in the main JFrame, homeButtonPanel was not displayed. When gamePlay was shown in the main JFrame, homeButtonPanel was displayed. I could not figure this out for so long.
After so much confusion and frustration, I realized that when I commented out the line that added the homeButtonPanel to the gamePlay panel, homeButtonPanel would be displayed on the gameRoom panel.
Why is it that I cannot add this JPanel to more than one additional JPanel?
(Also for reference I use a CardLayout to switch between displayed JPanels, if that matters)
//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);
Upvotes: 0
Views: 461
Reputation: 324098
I added homeButtonPanel to JPanel gameRoom, and then to JPanel gamePlay.
A component can only have a single parent, so no you can't add the same component to more than one panel.
So you need to create two instances of "homeButtonPanel" and then add an instance to each panel.
Another option is to have your main panel use a BorderLayout. Then you add the panel using the CardLayout to the CENTER of the BorderLayout. Then the "homeButtonPane" can be added to the PAGE_END of this panel, so now it will appear that the homeButtonPanel belongs to both panels in your CardLayout even when you swap panels.
Upvotes: 1