Java
Graphics Classes
Java contains many
predefined classes grouped into packages.
The Graphics class resides in the awt (abstract windowing
toolkit) package. This class contains
instance data regarding the current graphics ‘context’. The context includes the current drawing
color, font and transformation information (ie. rotation or scale). This class also provides methods for drawing
on the current drawing container (ie. your applet). If
your applet is going to use a Graphics object, you must import this class to
compile your file.
import
java.awt.Graphics;
Java has recently incorporated a Graphics2D
class, which provides more sophisticated drawing. The Graphics2D class inherits (extends) from
the Graphics class, meaning that a Graphics2D object provides all the methods
that the Graphics class does, in addition to it’s own.
Because the Graphics2D
class inherits from the Graphics class, a Graphics2D object IS a Graphics object . And so a
Graphics object can be transformed to a Graphics2D object with a simple ‘cast’:
Graphics2D obj2D = (Graphics2D) g; //assumes g is an object of type
Graphics
// class Graphics2D must also be imported
Three Graphics2D methods of immediate interest
are:
draw(Shape s) -
this method will draw a Shape s on the applet, using the current graphic
context. A shape is any object is of a class type
‘extending’ from the Shape class.
This will include classes like
Rectange2D.Double, Line2D.Double, Arc2D.Double , etc.
For example, if myRectangle is an object of type
Rectange.Double, it can be drawn:
obj2D.draw(myRectangle);
fill(Shape s) – this
method will fill a shape using, using the current graphic color. A shape
is the
same type of parameter used by draw.
obj2D.fill(myRectangle);
drawstring(String
str, int x, int y)
- this method can be used to place text on your applet
using
the current font settings and color. ‘str’ is the String to be drawn, the x and y
parameters
indicate the pixel position where the text in to begin
Specifying a position on
an applet in done in terms of an X position and a Y position. You can think of the applet in as having an
X,Y coordinate system, where each X,Y combination specify one pixel position.
0,0
largest_x, 0
i y gets larger à x gets larger |
0, largest_y largest_x,
largest_y
It is always good to look at the documentation
of a class when you are going to use it, so that you know what methods this
class provides. You should take a few
minutes to look at the Graphics2D class to view what is provided. The following link will take you to the
webpage where you can read the documentation of any of the classes included in
the Java library:
http://java.sun.com/j2se/1.4.2/docs/api/index.html