How do I draw 49 rectangles with nested loops with javafx?

Parker :

I have to use a double array to make 49 squares. What I have only given me one rectangle.

Rectangle[][] rectArray = new Rectangle[7][7];
//grid is a GridPane containing 49 rectangles.
GridPane grid = new GridPane();
//---- add 49 rectangles to the grid pane, it is recommended to use nested loops
for(int i = 0; i < rectArray.length; i++)
{

    for(int j = 0; j < rectArray.length; j++)
    {
        rectArray[i][j] = new Rectangle(470/7,390/7);
        rectArray[i][j].setStroke(Color.BLACK);
        rectArray[i][j].setFill(Color.WHITE);
        grid.getChildren().add(rectArray[i][j]);
     }

}
Alex :

Add

GridPane.setConstraints(rectArray[i][j], i, j);

right before you add the rectangle to the grid. Right now all the rectangles are put at the same position (0, 0), so they overlap and look like one.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=27069&siteId=1