后返回null。我有,增加了方块的GridPane构件board
一个初始化方法的BoardController类。此方法调用另一个在每个Square上设置鼠标事件侦听器的方法。GridPane getRowIndex我在JavaFX的制作熄灯游戏第二次使用
在事件处理程序,我用GridPane.getRowIndex
和GridPane.getColumnIndex
。然后我需要get a node by its GridPane coordinates,这是我在处理程序调用的函数中做的。但是,GridPane.getRowIndex
和GridPane.getColumnIndex
返回null。为什么?我该如何解决?
这是代码。
//set mouse handler on each square
private void setMouseHandlers()
{
ObservableList<Node> children = board.getChildren();
for(Node child : children)
child.setOnMouseClicked(new EventHandler() {
@Override
public void handle(Event event) {
int row = GridPane.getRowIndex(child); //fine
int col = GridPane.getColumnIndex(child); //fine
int up_row = row-1;
int down_row = row+1;
int left_col = col-1;
int right_col = col+1;
toggleNodeColor((Shape)child);
//this expression works but getrow/col index does not work in the next function calls even if I pass the children vector
//System.out.println(GridPane.getRowIndex(child) + " " + GridPane.getColumnIndex(child));
if(isInBounds(up_row,col)) toggleNodeColor((Shape) getNodeInGrid(up_row,col));
if(isInBounds(down_row,col)) toggleNodeColor((Shape) getNodeInGrid(down_row,col));
if(isInBounds(row,left_col)) toggleNodeColor((Shape) getNodeInGrid(row,left_col));
if(isInBounds(row,right_col)) toggleNodeColor((Shape) getNodeInGrid(row,right_col));
}
}
这里是getNodeInGrid
:
private Node getNodeInGrid(final int row, final int col)
{
Node result = null;
ObservableList<Node> children = board.getChildren();
for(Node child : children)
{
//FIXME these row/col idxs are all null even though the exact same code works in the setMouseHandlers() method
if((GridPane.getRowIndex(child) == row) && (GridPane.getColumnIndex(child) == col)) //NullPointer at this line
{
result = child;
break;
}
}
return result;
}
检查了这一点http://stackoverflow.com/questions/28320110/javafx-how-to-get-column-and-row-index-in-gridpane – Hamletkrita
我不知道这是如何帮助。在我的代码中,我在每个节点上都有一个监听器。在你连接的问题的答案中,监听器在GridPane上。另外,当我在SetMouseHandlers函数中调用getIndex方法时,getIndex方法适用于我,但不能在由它调用的另一个函数中再次调用它们时使用。 – BenK