Using Nested For Loops To Draw A Grid

This is too draw an x by y grid using awt (import for Java).

Although, you can easily port this to any other language as the syntax is so simple.

// This is used to draw a grid in Java. // Author: Unixkid.wordpress.com // drawGrid(5, 10, 11, Graphics g); // Uses java.awt at the moment, but can easily be changed. // // Here is the algorithm: private void drawGrid(int area, int rowsToPaint, int colsToPaint, Graphics g) { int x = 0; // Define x. int y = 0; // Define y. for (int row = 0; row <= rowsToPaint; row++) { // The first for loop, loops through how many rows you want. for(int col = 0; col <= colsToPaint; col++) { // The second one loops through each column. g.drawRect(x, y, area, area); // Java function, I used awt, but you can easily use Swing. x = x + area; // Tell the next square to be drawn at the end of this one. } y = y + area; // Tell the next square to be drawn on the next row. x = 0; // Woah! Almost forgot, make sure it starts at the beginning of the row. }

It’s easy huh? I’m only new at Java, so I’ll try find a way to do this in Swing.