我是新的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 from grid array作为:
for(int i = 0; i < 9; i++){
for(int j = 0; j < 9; j++){
add(grid[i][j]);
}
}
这是错误的,因此它抛出NullPointerException。请参阅IDE的控制台。解决方案是首先实例化grid数组,如下所示:
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]);
}
}