Search code examples
javajavafxjavafx-8

How to add 5x5 table of rectangle shape


I just joined and started learning JavaFX and am having trouble on how to add 5x5 table of rectangle shape with colors on it. Here is my progress:

public void start(Stage primaryStage) {
    GridPane grid = new GridPane();
    Random rand = new Random();
    ArrayList<String> colors = new ArrayList<String>();

    colors.add("ff0000");//red
    colors.add("#008000");//green
    colors.add("#0000ff");//blue
    colors.add("#ffff00");//yellow




    int row = 0;
    int col = 0;

    for (int i = 0; i < 26; i++) {
        Rectangle rect = new Rectangle(100, 100, 50, 50);
        rect.setFill(Color.web(colors.get(rand.nextInt(4))));
        rect.setStroke(Color.BLACK);

        grid.add(rect, row, col);
        if (row < 4) {
            row++;
        } 
        if (col < 4) {
            col++;
        }
    }

    grid.setAlignment(Pos.CENTER);
    Scene scene = new Scene(grid, 500, 500);

Here is the output:

Output

I want it to look like this:

Wanted Result


Solution

  • Write your loop as follows:

    for (int i = 0; i < 5; i++) {
        for (int j = 0; j < 5; ++)
            Rectangle rect = new Rectangle(100, 100, 50, 50);
            rect.setFill(Color.web(colors.get(rand.nextInt(4))));
            rect.setStroke(Color.BLACK);    
            grid.add(rect, i, j);
        }
    }