尝试将子级添加到具有行和列索引的GridPane。它们显示在gui中,但使用GridPane. getColumnIndex(节点)总是返回null。
GridPane grid = new GridPane();
for (int i = 0; i < 20; i++) {
for (int j = 0; j < 20; j++) {
grid.setGridLinesVisible(true);
Button myBtn = new Button("foo");
GridPane.setColumnIndex(myButton,i);
GridPane.setRowIndex(myButton,j);
grid.getChildren().add(myButton);
}
当我尝试使用这个算法时,我从javafx GridPane上的答案中检索特定的Cell内容,程序崩溃并出现NullPointerException。
private Node getNodeFromGridPane(GridPane gridPane, int col, int row)
{
for (Node node : gridPane.getChildren()) {
if (GridPane.getColumnIndex(node) == col && GridPane.getRowIndex(node) == row) {
return node;
}
}
return null;
}
为什么GridPane. getRowIndex()和GridPane.getColumnIndex()即使在调用setColumnIndex()和setRowIndex()后也返回null?
所以它似乎我得到了它的工作如果你运行它你会看到所有的按钮是红色白色或蓝色这是因为他们被发现
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); }
}