[英]Is it possible to add new JPanel to JFrame, after JFrame is loaded?
我正在用Java開發掃雷游戲。 在GUI設計期間,我遇到了一個問題。 這是我的游戲窗口。
灰色區域應該包含實際的雷區。 我想發生的是,在玩家單擊“開始游戲”之后,我想加載包含礦區實現的JPanel。 但是,似乎在JFrame加載后無法再添加任何JPanels,對嗎? 我嘗試在另一個線程中運行“我的”字段的添加(休眠幾秒鍾,然后添加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);
}
總結一下我的問題是,是否可以在運行時將新的JPanels添加到JFrame,如果可以的話,該怎么辦?
簡短的答案是,是的。 您需要調用revalidate
和repaint
來觸發布局,並在已更新的容器上進行繪畫傳遞。
更長的答案可能不是您執行此操作的方式。
除了您實際上從未start
過Thread
,Swing也不是線程安全的,並且您不應該在事件調度線程的上下文之外更新UI。
在您的情況下,另一種(更安全)的解決方案是使用Swing Timer
。 有關更多詳細信息,請參見如何使用Swing計時器 。
在開始游戲的動作偵聽器中,可以將jpanel添加到預先創建的框架中。 您可能還需要repaint()
或revalidate()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.