Search code examples
javajavafxgridpane

Javafx create rectangles in a loop


I am learning Javafx and am having trouble getting my for loop to create a new rectangle on each iteration. When I run the program it creates one rectangle at the top left position and that is it. My goal is to create a grid of rectangles based on the amount of columns, rows, pixels wide, and pixels tall specified. Everything is tested to work besides the creation of rectangles.

for(int i = 0; i < columns; ++i)
    {//Iterate through columns
        for(int j = 0; j < rows; ++j)
        {//Iterate through rows
            Color choice = chooseColor(rectColors);
            //Method that chooses a color

            rect = new Rectangle(horizontal*j, vertical*i, horizontal, vertical);
            //Create a new rectangle(PosY,PosX,width,height)

            rect.setStroke(choice);
            //Give rectangles an outline so I can see rectangles

            root.getChildren().add(rect);
            //Add Rectangle to board

        }
    }

I am trying to figure out why the rectangles aren't being created. Any help would be greatly appreciated.


Solution

  • I used the same program which you had. Try with this and check where you made the mistake. Also check the values you initialized.

    import javafx.application.Application;
    import javafx.scene.Scene;
    import javafx.scene.layout.AnchorPane;
    import javafx.scene.paint.Color;
    import javafx.scene.shape.Rectangle;
    import javafx.stage.Stage;
    
    public class RectangleDemo extends Application{
    
        @Override
        public void start(Stage stage) {
            AnchorPane root = new AnchorPane();
            Scene scene = new Scene(root);
            stage.setScene(scene);
    
            int columns = 20, rows = 10 , horizontal = 20, vertical = 20;
            Rectangle rect = null;
            for(int i = 0; i < columns; ++i)
            {//Iterate through columns
                for(int j = 0; j < rows; ++j)
                {//Iterate through rows
    //              Color choice = chooseColor(rectColors);
                    //Method that chooses a color
    
                    rect = new Rectangle(horizontal*j, vertical*i, horizontal, vertical);
                    //Create a new rectangle(PosY,PosX,width,height)
    
                    rect.setStroke(Color.RED);
                    //Give rectangles an outline so I can see rectangles
    
                    root.getChildren().add(rect);
                    //Add Rectangle to board
    
                }
            }
            scene.setRoot(root);
            stage.show();
    
        }
    
        public static void main(String[] args) {
            launch(args);
        }
    }
    

    I hope it will help you...