[英]getRowIndex always returning null
I set up the gridpane like so:我像这样设置了gridpane:
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));
}
}
And try to access it like so:并尝试像这样访问它:
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
}
}
It seems that GridPane.getRowIndex(node)
Always returns null
, thus causing a NullPointerException
and I cant figure out for the life of me why.似乎GridPane.getRowIndex(node)
总是返回null
,从而导致NullPointerException
并且我一生都无法弄清楚为什么。
A solution found here may be helpful: GridPane.getColumnIndex() returning null此处找到的解决方案可能会有所帮助: GridPane.getColumnIndex() 返回 null
The user was having the same problem and by changing how they added the elements to the gridpane, it worked.用户遇到了同样的问题,通过更改他们将元素添加到网格窗格的方式,它起作用了。
The answer provided by user Matt is:用户 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); }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.