Christian Baker
Christian Baker

Reputation: 389

Drawing a grid in java

I am trying to create a Cartesian Grid using a for loop. Below is part of my code so far; when I run it, it does not make a series of lines, but rather it produces a window that has what appears to be a white panel and it slows down my computer considerably. In fact, I have to start task manager and End Task it, because it won't even close normally.

public void paintComponent(Graphics g)
{
    int width = getWidth();
    int height = getHeight();
    super.paintComponent(g);

    int xstart=0;

    for(int i = 1; i <= 10; i = i++)
    {
        xstart = i*(width/10);
        g.drawLine(xstart, 0, xstart, height);
    }
}

Upvotes: 4

Views: 57606

Answers (3)

Bhushankumar Lilapara
Bhushankumar Lilapara

Reputation: 780

Actually you need two for loop one for row and and one for column instead you just used one, that is not enough to draw grid.

I have drawn grid as my assignment work, I have share it with you. It will help you to get find problem in your coding...

enter image description here

import java.awt.*;

class Grids extends Canvas {

    int width, height, rows, columns;

    Grids(int w, int h, int r, int c) {
        setSize(width = w, height = h);
        rows = r;
        columns = c;
    }

    @Override
    public void paint(Graphics g) {
        int k;
        width = getSize().width;
        height = getSize().height;

        int htOfRow = height / (rows);
        for (k = 0; k < rows; k++) {
            g.drawLine(0, k * htOfRow, width, k * htOfRow);
        }

        int wdOfRow = width / (columns);
        for (k = 0; k < columns; k++) {
            g.drawLine(k * wdOfRow, 0, k * wdOfRow, height);
        }
    }
}

public class DrawGrids extends Frame {

    DrawGrids(String title, int w, int h, int rows, int columns) {
        setTitle(title);
        Grids grid = new Grids(w, h, rows, columns);
        add(grid);
    }

    public static void main(String[] args) {
        new DrawGrids("Draw Grids", 200, 200, 2, 10).setVisible(true);
    }
}

Upvotes: 5

Two_Years_Experience
Two_Years_Experience

Reputation: 119

hey Guys i just used the little slice of your p to try and fix it and I just created a string art construction here is the code if you want to do it as well.int width = getWidth(); int height = getHeight();

   int xstart=0;

   for(int i = 1; i <= 10; i++)
   {

     xstart = i*(height/10);
     page.drawLine(xstart, 0, width, xstart);
   }

Upvotes: 0

David Conrad
David Conrad

Reputation: 16359

The increment in your for loop is wrong. Instead of

i = i++

It should be simply

i++

The postincrement operator returns the old value of i, which is being assigned back to i, so i never actually changes.

Upvotes: 3

Related Questions