java - GridPane getRowIndex 在第二次使用后返回 null

标签 java javafx-8

我正在 JavaFX 中制作 Lights Out 游戏。我有一个 BoardController 类,它具有一个初始化方法,该方法将 Squares 添加到 GridPane 成员 board 中。此方法调用另一个在每个 Square 上设置鼠标事件监听器的方法。

在事件处理程序中,我使用 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;
}

最佳答案

我发现问题了。

打印出 gridPane.getRowindex(child)==null 的结果表明存在一个“幽灵子项”,我自己没有将其添加到 GridPane 中。由于我没有添加它,因此 getRowIndex 返回 null,因为它从未设置过行和列。

快速而肮脏的解决方法是在 GetNodeInGrid() 中添加检查。

关于java - GridPane getRowIndex 在第二次使用后返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36733328/

相关文章:

使用相对路径的 Java Export JAR

java - 接口(interface)和 jaxb

javafx-2 - 如何检测按键

java - 数量/Axis : how to force an immediate update of internal state during layout?

javafx-2 - 如何在javaFX中第二次单击/选择时取消选择选定的表格行

java - 在java中搜索文本文件中的单词

java - 将图像从 JFrame 传递到另一个 JFrame

java - 套接字代理服务器重定向 url

java - 从 setOnAction 启动电子邮件客户端

java - 具有两列的 TreeView JavaFX 8