[英]GUI class not displaying anything on monitor
我是GUI的新手,我想知道為什么此代碼未顯示任何內容。 請記住,代碼不完整,請耐心等待,代碼有點長。
//imports
public class SudokuGame extends Frame{
private SudokuBoard sb = new SudokuBoard(this);
/**
* a button to restart game
*/
private Button b = new Button("Restart");
/**
* 9 x 9 buttons to store the numbers used in the game
*/
private Button[][] grid= new Button[9][9];
/**
* TextField used to store the remaining empty blocks
*/
private TextField t;
/**
* Constructor
* @param ssm
*/
public SudokuGame(SomeSudokuMatrix ssm) {
/**
* sets window's name
*/
super( "Sudoku" );
/**
* sets background color
*/
setBackground( Color.WHITE );
/**
* adds SudokuBoard to the SudokuGame which extends frame
*/
add( sb, BorderLayout.CENTER );
/**
* initialize the remaining blocks to TextField
*/
t = new TextField("Remain:" + sb.getEmpty());
/**
* new panel
*/
Panel p = new Panel();
/**
* sets panel size to 100 x 10
*/
p.setSize(100,10);
/**
* sets restart button size to 10 x 5 and location to 48, 5
*/
b.setBounds(48,5,10,5);
/**
* adds restart button to the Panel
*/
p.add( b );
/**
* adds panel to south
*/
add( p, BorderLayout.SOUTH );
/**
* adds ActionListner to restart button
*/
b.addActionListener( sb );
/**
* adds TextField to the Panel
*/
p.add(t);
/**
* Sets the TextField size to 10 x 5 and location to 53, 5
*/
t.setBounds(53,5,10,5);
/**
* adds the buttons that hold the values
*/
for(int i = 0; i < 9; i++){
for(int j = 0; j < 9; j++){
grid[i][j]=new Button(null);
add(grid[i][j]);
}
}
/**
* Automatically resizing
*/
pack();
/**
* Shows SudokuGame
*/
setVisible(true);
/**
* Shows the Panel
*/
p.setVisible(true);
}
/**
* sets the label of the button
*
* @param s String to add to the button
* @param i the position
* @param j the position
*/
public void setText(String s, int i, int j){
/**
* if the button is not empty sets the label of the button
*/
if(!s.equals("-1")){
grid[i][j].setLabel(s);
}
} //to do: change TextField when filling empty block
public void setText(String s){
t.setText(s);
}
}
這是GUI類(框架),沒有畫布,動作偵聽器或運行游戲的任何其他類。
你寫
private Button[][] grid= new Button[9][9];
它應該是
private Button[][] grid= new Button[9][];
接下來,您直接從網格數組開始添加Button,如下所示:
for(int i = 0; i < 9; i++){
for(int j = 0; j < 9; j++){
add(grid[i][j]);
}
}
這是錯誤的,因此拋出NullPointerException。 請參閱IDE的控制台。 解決方案是首先實例化網格數組,如下所示:
for(int i = 0; i < 9; i++){
grid[i]=new Button[9];
}
for(int i = 0; i < 9; i++){
for(int j = 0; j < 9; j++){
grid[i][j]=new Button("SomeLabel");
}
}
初始化網格數組后,將按鈕添加到框架,如下所示:
for(int i = 0; i < 9; i++){
for(int j = 0; j < 9; j++){
add(grid[i][j]);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.