Надеюсь, вы все поможете мне понять эту тайну. Я создал панель JPanel с кнопкой «Вернуться» и красивой компоновкой, которая мне понравилась. Я хотел добавить эту панель JPanel (с этого момента я буду называть ее homeButtonPanel) в несколько других панелей JPanel, потому что я хочу, чтобы все они имели кнопку «Вернуться».
Я добавил homeButtonPanel в JPanel gameRoom, а затем в JPanel gamePlay. Когда gameRoom отображался в основном JFrame, homeButtonPanel не отображался. Когда gamePlay отображался в основном JFrame, отображалась панель homeButtonPanel. Я так долго не мог в этом разобраться.
После столько путаницы и разочарования я понял, что когда я закомментировал строку, добавляющую homeButtonPanel на панель gamePlay, homeButtonPanel будет отображаться на панели gameRoom.
Почему я не могу добавить эту панель JPanel более чем в одну дополнительную панель JPanel?
(Также для справки я использую CardLayout для переключения между отображаемыми панелями JPanel, если это имеет значение)
//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);