Draw grid on JFrame

Complete source code below will show you, how to draw grid on a JFrame.

****************************************************************************
COMPLETE SOURCE CODE FOR : DrawGridOnJFrame.java
****************************************************************************


import javax.swing.JFrame;

import java.awt.Graphics;

public class DrawGridOnJFrame extends JFrame
{
//Constructor
public DrawGridOnJFrame()
{
//Set JFrame title to ( Draw grid on JFrame )
setTitle("Draw grid on JFrame");

//Set JFrame size to :
//Width : 400 pixels
//Height : 400 pixels
setSize(400,400);

//Set JFrame default close operation
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//Make JFrame visible
setVisible(true);
}


/**
*To draw grid line on JFrame we will override it's paint method.
*We will draw grid with size 10 pixels width and 10 pixels height for each grid box
**/
public void paint(Graphics g)
{
//Override paint method in superclass
super.paint(g);

//Get current JFrame width
int frameWidth=getSize().width;

//Get current JFrame height
int frameHeight=getSize().height;

int temp=0;

//Draw vertical grid line with spacing between each line equal to 10 pixels
while(temp<frameWidth)
{
temp=temp+10;
g.drawLine(temp,0,temp,frameHeight);
}

temp=0;

//Draw horizontal grid line with spacing between each line equal to 10 pixels
while(temp<frameHeight)
{
temp=temp+10;
g.drawLine(0,temp,frameWidth,temp);
}
}

//Main method
public static void main(String[]args)
{
DrawGridOnJFrame dgojf=new DrawGridOnJFrame();
}
}


****************************************************************************
JUST COMPILE AND EXECUTE IT
****************************************************************************

RELAXING NATURE VIDEO