Drawing a Grid

How would I draw a grid? I mean something like this: http://img508.imageshack.us/img508/7054/javagriddr9.png (ignore the uneven spacing). Should I just draw a series of horizontal and vertical lines?

I'm tring to make a tile-map editor, and the tiles/map is split into pixels. Each box represents a pixel (zoomed in). The user can draw within the grid lines, individual pixels, etc.

[397 byte] By [bfrbfra] at [2007-11-27 6:38:12]
# 1

Do you know how to override JPanels paintComponent method and use drawing tools? If not post back. Otherwise one way would be to:

for(int i = 0; i < num_gridlines; i++){

position = startpos + (i * distance)

gfx.drawLine(...)

}

http://java.sun.com/j2se/1.4.2/docs/api/java/awt/Graphics2D.html

TuringPesta at 2007-7-12 18:06:47 > top of Java-index,Java Essentials,Java Programming...
# 2
Oh, I don't know how to override the JPanels' paintComponent method and using drawing tools. I've never done that before.(Thanks for helping me!)
bfrbfra at 2007-7-12 18:06:47 > top of Java-index,Java Essentials,Java Programming...
# 3

> (Thanks for helping me!)

Woops! I forgot about this thread.

Well anyway, this is one way. There might be a better way.

Good luck!

import javax.swing.*;

import javax.swing.event.*;

import java.awt.*;

import java.awt.event.*;

public class GridPanelTest{

public static void main(String[] args){

new GridPanelTest();

}

public GridPanelTest(){

panel = new GridPanel();

frame = new JFrame();

frame.setContentPane(panel);

frame.setSize(500, 500);

frame.setLocationRelativeTo(null);

frame.setVisible(true);

}

public class GridPanel extends JPanel{

public GridPanel(){

this.setBackground(Color.WHITE);

}

public void paintComponent(Graphics g){

super.paintComponent(g);

Graphics2D gfx = (Graphics2D)g;

gfx.setRenderingHint(RenderingHints.KEY_ANTIALIASING,

RenderingHints.VALUE_ANTIALIAS_ON);

gfx.setStroke(thick);

gfx.setPaint(Color.RED);

for(int i = 0; i < numRows; i++){

int pos = (int)(((double)this.getHeight() / (double)numRows) * (double)i);

gfx.drawLine(0, pos, this.getWidth(), pos);

}

for(int j = 0; j < numColumns; j++){

int pos = (int)(((double)this.getWidth() / (double)numColumns) * (double)j);

gfx.drawLine(pos, 0, pos, this.getHeight());

}

}

int numRows = 4;

int numColumns = 3;

BasicStroke thick = new BasicStroke(2);

}

JFrame frame;

GridPanel panel;

}

TuringPesta at 2007-7-12 18:06:47 > top of Java-index,Java Essentials,Java Programming...