Book Home Java Enterprise in a Nutshell Search this book

Chapter 4. Graphics with AWT and Java 2D


Graphics Before Java 2D
Java 2D Graphics Attributes and Operations
The Coordinate System
Stroking Lines
Blending Colors with AlphaComposite
Rendering Hints
Fonts and Text
Buffered Images
Transformations with AffineTransform
Color Spaces

Java 1.0 and Java 1.1 included basic graphics capabilities as part of the AWT (Abstract Windowing Toolkit). In the Java 2 platform, these capabilities have been greatly enhanced with the introduction of Java 2D. While Java 2D is part of the JFC (the Java Foundation Classes), the Java 2D API is implemented in the same java.awt package as the original Java graphics classes.

This chapter begins by documenting the original Java graphics model, which is still required for Java 1.1 applications, applets, and Personal Java applications. The chapter then moves on to detail the enhanced features provided by Java 2D. This chapter can provide only an introduction to the various features of Java 2D; for more complete information, see Java 2D Graphics, by Jonathan Knudsen (O'Reilly).

4.1. Graphics Before Java 2D

All graphics operations in Java are performed using a java.awt.Graphics object. The Graphics object serves three purposes:

The graphics capabilities of Java before Java 2D can be neatly summarized by listing the graphics attributes and operations supported by the Graphics object. Table 4-1 lists the attributes, and Table 4-2 lists the operations.

Table 4-1. Attributes of the Graphics Class

Attribute Type Description
Color Color

Set with setColor().

Font Font

Set with setFont(). Only a small number of standard fonts are available.

Clipping region Rectangle

In Java 1.1, set with setClip(). Use clipRect() to set to the intersection of the current clipping region and a rectangle. setClip() takes a Shape object, but prior to Java 1.2, the clipping region is, in practice, restricted to rectangles.

Origin Point

Use translate() to move the origin. The default origin is in the upper-left corner of the drawing region, with X coordinates increasing to the right and Y coordinates increasing down.

Paint mode boolean

setXORMode() puts the Graphics object into the infrequently used XOR mode, while setPaintMode() restores the default drawing mode.

Background color Color

This attribute is used only by the clearRect() method, and its value cannot be set. When drawing into a Component, the background color is the value of the background attribute of the component. The value is undefined when drawing into off-screen images.

Table 4-2. Operations of the Graphics Class

Operation Methods Attributes Used
Line drawing

drawLine(), drawPolyline()

color, origin, clip, paint mode

Shape drawing

drawArc(), drawOval(), drawPolygon(), drawRect(), drawRoundRect(), draw3DRect()

color, origin, clip, paint mode

Shape filling

fillArc(), fillOval(), fillPolygon(), fillRect(), fillRoundRect(), fill3DRect()

color, origin, clip, paint mode

Text drawing

drawBytes(), drawChars(), drawString()

color, font, origin, clip, paint mode

Image drawing (blitting)

drawImage() (various versions)

origin, clip, paint mode



origin, clip, background color

4.1.1. Line Drawing

An important point to notice in Table 4-1 is that there is no attribute for line width. Prior to Java 2D, Java can only draw lines that are a single pixel wide. This is perhaps the single largest limitation of the Java 1.0 and Java 1.1 graphics environments.

4.1.2. Colors

Colors are represented by the java.awt.Color class. In Java 1.0 and Java 1.1, this class represents colors in the RGB color space. It has constructors that allow you to specify red, green, and blue color coordinates as integers or as floating-point values. The class defines a static method that allows you to create a Color using coordinates from the HSB (hue, saturation, brightness) color space. It also defines a number of constants that represent colors by their common names, such as and Color.white.

java.awt.SystemColor is a subclass of Color introduced in Java 1.1. The class has no public constructor but defines a number of SystemColor constants that represent colors used on the system desktop (for systems that support a system desktop color palette). For example, SystemColor.textHighlight represents the color used for highlighted text

4.1.3. Fonts

Fonts are represented with the java.awt.Font class. A Font object is created by specifying the name, style, and point size of the desired font. In an attempt to promote platform independence, Java 1.0 supports only a handful of standard font names. Java 1.1 supports the same fonts but provides new preferred symbolic names for them. The fonts supported prior to Java 2D are listed in Table 4-3.

Table 4-3. Font Names in Java 1.0 and Java 1.1

Java 1.0 Name Preferred Name in Java 1.1
TimesRoman Serif
Helvetica SansSerif
Courier Monospaced
Symbol Symbol
Dialog Dialog
DialogInput DialogInput

Fonts can be displayed in any of four possible font styles, which are represented by the symbolic constants listed in Table 4-4.

Table 4-4. Java Font Styles

Style Java Constant
plain Font.PLAIN
italic Font.ITALIC
bold Font.BOLD
bolditalic Font.BOLD + Font.ITALIC

Font sizes are specified in points. The Font() constructor accepts an integer argument, so fractional point sizes are not supported in Java 1.0 and 1.1. If the native platform does not support scalable fonts, the returned font may have a different size than what you requested.

4.1.4. Font Metrics

If you need to figure out how big a piece of text will be, you can call the getFontMetrics() methods of a Graphics object and pass in the desired font. This returns a FontMetrics object. The getHeight() method returns the line height for the font, which can be further broken down into the font ascent and descent, returned by getAscent() and getDescent(), respectively. To measure the horizontal dimension of text, use charWidth() and stringWidth().

4.1.5. Images

Images are represented by the java.awt.Image class. Working with images in Java 1.0 and Java 1.1 is a little tricky because the image processing model of those releases is based on streaming image data being loaded across a network. This treatment of images allows images to be partially displayed before they are fully loaded, but makes working with images somewhat more difficult.

All of the drawImage() methods of the Graphics objects require an java.awt. image.ImageObserver object. This is the object that handles things if you try to draw an image that is not fully loaded. Fortunately, java.awt.Component implements ImageObserver, so you can use any Component or Applet object for this method argument.

If are writing an applet and want to load a predefined image from a URL, you can use the getImage() method defined by the java.applet.Applet class. This method begins downloading the specified image and returns an Image object to you immediately.

If you are writing a standalone application and want to load a predefined image from a file or URL, use one of the getImage() or createImage() methods of the java.awt.Toolkit class:


Like the getImage() method of Applet, these Toolkit methods start loading the image and immediately return an Image object. The image formats supported by these Applet and Toolkit methods are implementation dependent. Most implementations support common formats, such as GIF (including transparent GIF), JPEG, and XBM.

To ensure that an Image object is fully loaded before you use it, you can create a java.awt.MediaTracker object, pass your Image to its addImage() method, then call the waitForAll() method.

To create an empty off-screen image that you can draw into and copy pixels out of, call the createImage() method of the Component with which you plan to use the image and pass in the desired width and height of the image. To draw into the image, you have to obtain a Graphics object by calling the getGraphics() method of the image. Images created in this way are often used for double-buffering, to produce smoother animations or graphical updates.

The java.awt.image package contains classes that support rudimentary image processing and filtering. Java 2D implements more powerful image-processing techniques, so the Java 1.0 model is not described here.

Library Navigation Links

Copyright © 2001 O'Reilly & Associates. All rights reserved.