Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drawing a grid in java

Tags:

java

draw

grid

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);
    }
}
like image 806
Christian Baker Avatar asked Mar 23 '23 04:03

Christian Baker


2 Answers

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);
    }
}
like image 181
Bhushankumar Lilapara Avatar answered Apr 02 '23 23:04

Bhushankumar Lilapara


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.

like image 33
David Conrad Avatar answered Apr 02 '23 23:04

David Conrad