The Task: Try this one yourself - Write an applet that displays a chess board on the screen. So what I am asking for is as in Figure 7.3, “ChessBoard Applet”. Id don't expect you to have to draw 64 separate boxes, so I am expecting that you will use your coding skills to minimise the amount of code to be written.
You can see it running (not that it does much!) here - The Chess Board Applet
Some Useful Information: Some of the methods that can be used with the
Graphics
object g are:
drawLine(int x1, int y1, int x2, int y2)
Draws a line from (x1,y1) to (x2,y2) in the current colour.
fillRect(int x1, int y1, int width, int height)
Fills a rectangle from (x1,y1) with a
width and height in the current colour.
setColor(Color c)
Changes the current colour to a new Color
object.
Where Color
is a class in java.awt.Color
that has certain defined
colors, for example g.setColor(Color.red)
. So for example to draw a red line the code might look like:
(DrawRedLine.java
)
1 2 3 import java.awt.Graphics; 4 import java.awt.Color; 5 import java.applet.Applet; 6 7 public class DrawRedLine extends Applet 8 { 9 public void paint(Graphics g) 10 { 11 g.setColor(Color.red); 12 g.drawLine(10,10,50,50); 13 } 14 } 15 16
This code will result in an applet that looks like Figure 7.4, “DrawRedLine Applet”.
Solution:
My Solution is here (there are many), but don't look at it until you have had a good attempt!
Chess Example Solution
© 2006
Dr. Derek Molloy
(DCU).