Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Java applet to draw grid

810103Dec 5 2010 — edited Dec 6 2010
Hi, I have an exam Tuesday and an assignment Ive done before is to draw a chessboard pattern, but a past question has been to draw a grid pattern with red horizontal lines and blue vertical ones.

It must display an input dialog asking the user how many lines to draw along each side and the pattern should size itself to fit exactly with the applet area.

It says to use setColor(Color c) and fillRect(x1,y1,x2,y2): draws lines between (x1, y1) and (x2,y2)

Here's my code for the chessboard:
import java.awt.*;
import java.applet.*;

public class Q2_chessboard extends Applet {
	public void paint(Graphics g) 
	{

		int row, column, x, y;
		
		//for every row on the board
		for (row = 0;  row < 8;  row++ ) 
		{
			//for every column on the board
			for (column = 0;  column < 8;  column++) 
			{
				//Coordinates
				x = column * 20;
				y = row * 20;
				
				//square is red if row and col are either both even or both odd.
				if ( (row % 2) == (column % 2) ) 
					g.setColor(Color.red);
				
				else
					g.setColor(Color.black);
				g.fillRect(x, y, 20, 20);
			} 
		} 
	}
}
But Ive tried for ages and cant turn this code into the code needed for the past question.

I know I have to use:
		//Gets size of Applet
		int appletHeight = getSize().height;
		int appletWidth = getSize().width;
But cant wrap my head around it where to use it.

I had replaced the numerical values of row and column with
		input = JOptionPane.showInputDialog("Enter number lines to draw on each side:");
		lines = Integer.parseInt(input);
but it came asked twice and I couldnt expand the applet without it asking for input again.
This post has been answered by walterln on Dec 6 2010
Jump to Answer
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jan 3 2011
Added on Dec 5 2010
2 comments
4,498 views