[英]JFrame freezes after calling getContentPane().removeAll()
這個問題的標題不言而喻。 我正在使用JFrame復制掃雷器,並且剛剛完成了開始屏幕,玩家可以選擇游戲大小。 當單擊一個按鈕時,框架應清除為游戲屏幕准備。 當我單擊一個按鈕時,該按鈕保持“已按下”狀態,並且JFrame凍結,因此我必須將其關閉。 我究竟做錯了什么?
碼:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Minesweeper extends JFrame implements ActionListener{
JLabel starttitle;
ButtonObject[] gamefield;
JFrame frame;
JPanel startscreen;
JPanel gamescreen;
int gamesize;
JButton ten;
JButton tfive;
JButton fifty;
GridLayout layout;
public Minesweeper()
{
frame = new JFrame("Minesweeper");
frame.setSize(500,500);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);;
startscreen = new JPanel();
startScreen();
}
public void startScreen()
{
ten = new JButton("10 x 10");
tfive = new JButton("25 x 25");
fifty = new JButton("50 x 50");
starttitle = new JLabel("Welcome to minesweeper. Click a game size to begin.");
frame.add(startscreen);
startscreen.add(starttitle);
startscreen.add(ten);
startscreen.add(tfive);
startscreen.add(fifty);
ten.addActionListener(this);
tfive.addActionListener(this);
fifty.addActionListener(this);
}
public void gameScreen()
{
frame.getContentPane().removeAll();//freezes JFrame
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==ten)
{
gamesize = 10;
gameScreen();
}
else if(e.getSource()==tfive)
{
gamesize = 25;
gameScreen();
}
else if(e.getSource()==fifty)
{
gamesize = 50;
gameScreen();
}
else
{
System.out.println("Fatal error");
}
}
public static void main(String[] args)
{
new Minesweeper();
}
}
它不會凍結,請調用框架的repaint()
方法,所有組件都將清除。
只需在actionPerformed()
添加下一行:
frame.repaint();
像這樣..
public void gameScreen()
{
frame.getContentPane().removeAll();
frame.repaint();
}
JFrame
的默認LayoutManager
是Borderlayout
對已經可見的Swing GUI的所有更改(添加,刪除,調整大小,修改)必須適當地通知使用過的LayoutManager
JFrame
標准通知者是frame.(re*)validate
和frame.repaint()**
,
*-在Java7和更高版本中
**-並非在所有情況下都是必需的(對於JTextComponents
, JFrame.pack()
,ei),默認情況下也最好使用此代碼行
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.