Thank you for visiting Blazing Games

Drawing with the graphics class

If you are planning on drawing stuff there are two routes you can take. The easiest way is to draw directly to the applet window by overriding the applet's paint method. Another, more official way, is to create a class that overrides one of the existing components. The best component for overriding for drawing things is the canvas component as it is specifically designed to be overridden for classes that draw things.

For the demo applet, I am overriding the paint method and drawing directly to the applet's window. The paint method starts off by defining variables that are to be used

Next it draws a grid. Drawing lines are done by using the line method of the graphics class, which was passed to the method as the variable g. The line will be drawn in the current graphics color. This color can be changed by using the setColor method. There are constant colors defined in the Color class, so it is easy to use many of the more common colors.

Text is drawn using the drawText method. To get information on the current font, a FontMetrics object can be obtained by using the getFontMetrics method. The FontMetrics class holds all sorts of information about the font, with the stringWidth method being useful for getting the width in pixels that a particular string will require. This information is vital for properly positioning text. It should be noted that strings are placed via baseline.

Captions are drawn like the other text, but with a different color. Like with fonts, the text color is the color that is currently set in the graphics class. To change the color text is drawn in, simply change the current color.

Previous Chapter 4 Contents Page 8 of 10 Book Contents Next

About - Privacy Policy - Contact - Links - FAQ
Copyright © 2003-2006 Blazing Games Inc. All Rights Reserved