Chapter 12. Graphics
Java
1.0 and 1.1 provided rudimentary graphics capabilities through the
java.awt.Graphics class and associated classes,
such as java.awt.Color and
java.awt.Font. In Java 1.2 and later, the Java 2D
API provides state-of-the-art, two-dimensional graphics facilities
using the java.awt.Graphics2D class (a subclass of
Graphics) and associated classes, such as
java.awt.BasicStroke,
java.awt.GradientPaint,
java.awt.TexturePaint,
java.awt.AffineTransform, and
java.awt.AlphaComposite.This chapter demonstrates
using all these classes; it shows how you can draw graphics with and
without the Java 2D API. The key class for all graphics operations is
Graphics (or in the Java 2D API, its subclass,
Graphics2D). The purpose of this class is
threefold:
- It defines the drawing surface
A Graphics object can represent the on-screen
drawing area within an AWT (or Swing) component. It can also
represent an off-screen image you can draw into or a piece of paper
to be printed on a printer.- It defines drawing methods
All primitive graphics operations, such as drawing lines, filling
shapes, and displaying text, are performed using methods of the
Graphics class.- It defines attributes used by the drawing methods
Various methods of the Graphics class can set the
font, color, clipping region, and other attributes used when
performing graphics operations, such as drawing lines, filling
shapes, and displaying text. The values of these graphical attributes
are often instances of AWT classes, such as Color,
Font, Stroke,
AffineTransform, and so on.
The graphics capabilities of Java are
intimately wed with the AWT. As such, the Graphics
and Graphics2D classes are part of the
java.awt package, as are all the associated
classes that define graphical attributes. As we discussed in Chapter 11, the central class of the AWT is
java.awt.Component. Component
is the basic building block of all graphical user interfaces in Java.
A Graphics object represents a drawing surface,
but Java doesn't allow you to draw directly to the
computer screen. Instead, it restricts you to drawing within the
confines of a Component, using a
Graphics object that represents the drawing
surface of that component. Thus, to do graphics in Java, you must
have a Component (or a
java.applet.Applet, a Component
subclass) to draw into. Drawing is usually done by subclassing a
specific component and defining a paint( ) method
(or a paintComponent( ) method, for Swing
components). The examples in this chapter have been structured to
focus on the mechanics of drawing, rather than the mechanics of GUI
creation, but you will still see some code that handles GUI-related
tasks.