首页 > 解决方案 > getRowIndex 总是返回 null

问题描述

我像这样设置网格窗格:

for (int row = 0; row < mainBoard.getRows(); row++){
    for (int column = 0; column < mainBoard.getColumns(); column++) {
        mainBoard.setStatusArray(row, column, 0);
        Pane pane = new Pane();
        GridPane.setRowIndex(pane, row);
        GridPane.setColumnIndex(pane, column);
        gridpane.getChildren().add(new Pane());
        System.out.println(GridPane.getRowIndex(pane));
    }
}

并尝试像这样访问它:

ObservableList<Node> childrens = gridpane.getChildren();
    for (Node node : childrens) {
        if (node instanceof Pane
            && GridPane.getRowIndex(node) == 1        <------------- line of error
            && getColumnIndex(node) == 1) {
                // Do stuff
    }
}

似乎GridPane.getRowIndex(node)总是返回null,因此导致NullPointerException我一生都无法弄清楚为什么。

标签: javajavafx

解决方案


此处找到的解决方案可能会有所帮助:GridPane.getColumnIndex() 返回 null

用户遇到了同样的问题,通过改变他们将元素添加到网格窗格的方式,它起作用了。

用户 Matt 提供的答案是:

import javafx.application.Application;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;


public class Main extends Application {

    @Override
    public void start(Stage primaryStage) {

        GridPane grid = new GridPane();
        grid.setGridLinesVisible(true);

        for (int i = 0; i < 20; i++) {
            for (int j = 0; j < 20; j++) {
                grid.add(new Button("foo"),i,j);
                //                Button myBtn = new Button("foo");
                //                GridPane.setColumnIndex(myBtn, i);
                //                GridPane.setRowIndex(myBtn, j);
                //                grid.getChildren().add(myBtn);
            }
        }


        Scene scene = new Scene(grid);

        Stage stage = new Stage();
        stage.setScene(scene);
        stage.show();

        String[] colors = {"-fx-background-color: red;", "-fx-background-color: blue;", "-fx-background-color: white;"};
        for (int i = 0; i < 20; i++) {
            for (int j = 0; j < 20; j++) {
                Node node = getNodeFromGridPane(grid,i,j);
                if(node instanceof Button)
                    node.setStyle(colors[(int) (Math.random() * 3)]);
            }
        }
    }

    private Node getNodeFromGridPane(GridPane gridPane, int col, int row) {
        for (Node node : gridPane.getChildren())
            if (GridPane.getColumnIndex(node) != null
                    && GridPane.getColumnIndex(node) != null
                    && GridPane.getRowIndex(node) == row
                    && GridPane.getColumnIndex(node) == col)
                return node;
        return null;
    }

    public static void main(String[] args) { launch(args); }
}

推荐阅读