【发布时间】:2015-07-11 20:21:54
【问题描述】:
希望大家能帮助我理解这个谜团。我创建了一个 JPanel,其中包含一个“返回”按钮,并且有一个我喜欢的漂亮布局。我想将这个 JPanel(从这里开始我将其称为 homeButtonPanel)添加到其他几个 JPanel,因为我希望它们都有一个“返回”按钮。
我将 homeButtonPanel 添加到 JPanel gameRoom,然后添加到 JPanel gamePlay。在主 JFrame 中显示 gameRoom 时,未显示 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);
【问题讨论】:
-
After link : "每个 GUI 组件只能包含一次。如果一个组件已经在一个容器中,并且您尝试将其添加到另一个容器中,则该组件将从第一个容器中删除然后添加到第二个”
标签: java user-interface jpanel jbutton boxlayout