我在这里傻眼了。我有一个JPanel
(defBoardPanel) 我要添加到父级JPanel
(GamePanel) 中,如下所示:
public GamePanel(SetupBoard sb) {
this.setLayout(new BorderLayout());
// this.setBackground(Color.yellow);
JPanel defBoardPanel = new JPanel();
defBoardPanel.setBackground(Color.yellow);
for (int r = 0; r < sb.boardSize; r++){
for (int c = 0; c < sb.boardSize; c++){
Cell c = new Cell(r, c);
c.label.setOpaque(true);
if (sb.getCell(r, c).status == sb.getCell(r,c).status.occupied){
c.label.setBackground(Color.black);
System.out.println("LABEL IS OCCUPIED");
}
else {
c.label.setBackground(Color.white);
}
defBoardPanel.add(c.label);
}
}
defBoardPanel.revalidate();
defBoardPanel.setVisible(true);
this.add(defBoardPanel, BorderLayout.WEST);
this.revalidate();
this.setVisible(true);
该面板将被添加到一个 JFrame(MainFrame)中,如下所示。当应用程序启动时,JFrame 会显示不同类型的面板 (SetupBoard),用户可以使用它来设置他们的游戏板。当他们点击“接受”时,MainFrame 的 StartGame() 方法被调用,它应该显示上面的 JPanel。
public MainFrame() {
this.setLayout(new BorderLayout());
this.setSize(500, 500);
SetupBoard sb = new SetupBoard(10, this);
this.setContentPane(sb);
}
void startGame(SetupBoard sb){
GamePanel gp = new GamePanel(sb);
this.setContentPane(gp);
this.revalidate();
}
我的问题是子面板(defBoardPanel)没有显示。GamePanel 本身显示(我已经使用setBackground(Color.yellow)
您看到的注释掉的方法进行了验证),但不是我添加到它的面板。
我在这里忽略了什么愚蠢的错误?
编辑:正在从 SetupBoard 类中调用 startGame():
void startGame(){
mf.startGame(this);
}
其中 mf 是对创建 SetupBoard 实例的 MainFrame 的引用。GamePanel 完全显示的事实证实了它被正确调用。