java - 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
我一生都无法弄清楚为什么。
解决方案
此处找到的解决方案可能会有所帮助: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); }
}
推荐阅读
- android - VectorDrawable: How to resize the vectordrawable dynamically
- php - composer install gives errors on Gitlab CI
- c++ - C++ using arrays as multidimensional despite initalising it as 1D with pointer
- ssas - 如何访问存储在 DAX 变量中的表的列
- reactjs - 关闭反应模式时出错
- easing - MLT - How to add easing to transition or filter?
- git - git push 上图片旁边的 % 是什么?
- pytorch - 如何在 Pytorch 中学习嵌入并在以后检索它
- docker - Kubernetes 节点 ulimit 设置
- angular - Angular 5 SSO 读取请求标头