【发布时间】:2017-10-17 11:53:09
【问题描述】:
我正在用 Java 构建一个扫雷游戏。在 GUI 设计期间,我遇到了一个问题。这是我的游戏窗口。
应该包含实际雷区的灰色区域。我想要发生的是,在玩家点击开始游戏后,我想加载包含雷区实现的 JPanel。但是,似乎在 JFrame 加载后我无法再添加任何 JPanel,我是对的吗?我尝试在不同的线程中运行添加雷区(睡眠几秒钟,然后添加 JPanel),只是看看是否可能,没有结果。
public GameWindow(){
super("Minesweeper");
this.setLayout(new BorderLayout());
this.gamePanel = new GamePanel(new GridLayout(BOARD_SIZE,BOARD_SIZE,1,1));
this.timerPanel = new TimerPanel(new BorderLayout(15,15));
this.timerPanel.initializeFlagLabel(8);
this.mineField = new Button[BOARD_SIZE][BOARD_SIZE];
int buttonCounter = 0;
for(int i = 0; i < BOARD_SIZE; i ++){
for(int j = 0; j < BOARD_SIZE; j++){
mineField[i][j] = new Button();
mineField[i][j].setName(Integer.toString(buttonCounter++));
mineField[i][j].setBackground(Color.GRAY);
mineField[i][j].setPreferredSize(new Dimension(10,10));
mineField[i][j].addMouseListener(this);
gamePanel.add(mineField[i][j]);
}
}
Container container = getContentPane();
container.add(timerPanel,BorderLayout.PAGE_START);
container.add(new MenuPanel(this), BorderLayout.WEST);
new Thread(new Runnable(){//Here I want to wait for the JFrame to
//load and then to add the gamePanel.
public void run(){
try {
Thread.sleep(4000);
container.add(gamePanel, BorderLayout.CENTER);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
this.setSize(800,640);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
this.setVisible(true);
}
总结一下我的问题是,是否可以在运行时向 JFrame 添加新的 JPanel,如果可以,我该怎么做?
【问题讨论】: