2016-04-20 19 views
1

后返回null。我有,增加了方块的GridPane构件board一个初始化方法的B​​oardController类。此方法调用另一个在每个Square上设置鼠标事件侦听器的方法。GridPane getRowIndex我在JavaFX的制作熄灯游戏第二次使用

在事件处理程序,我用GridPane.getRowIndexGridPane.getColumnIndex。然后我需要get a node by its GridPane coordinates,这是我在处理程序调用的函数中做的。但是,GridPane.getRowIndexGridPane.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; 
} 
+0

检查了这一点http://stackoverflow.com/questions/28320110/javafx-how-to-get-column-and-row-index-in-gridpane – Hamletkrita

+0

我不知道这是如何帮助。在我的代码中,我在每个节点上都有一个监听器。在你连接的问题的答案中,监听器在GridPane上。另外,当我在SetMouseHandlers函数中调用getIndex方法时,getIndex方法适用于我,但不能在由它调用的另一个函数中再次调用它们时使用。 – BenK

回答

0

我发现这个问题。

打印出来的gridPane.getRowindex(child)==null结果表明,有一个“鬼孩子”,一个我没有加入到GridPane自己。由于我没有添加它,所以getRowIndex在它上面返回null,因为它没有设置它的行和列。

快速“N脏的解决办法是在GetNodeInGrid()添加检查。