Overview of the Java 2D API |
The basic rendering mechanism is the same as in previous versions of the JDK--the drawing system controls when and how programs can draw. When a component needs to be displayed, that component'spaint
orupdate
method is automatically invoked with an appropriateGraphics
context.The Java 2D API introduces a new type of
Graphics
object,java.awt.Graphics2D
Graphics2D
extends theGraphics
class to provide access to the enhanced graphics and rendering features of the Java 2D API.To use Java 2D API features, you cast the
Graphics
object passed intoa
component's rendering method to aGraphics2D
object. For example:public void Paint (Graphics g) { Graphics2D g2 = (Graphics2D) g; ... }Graphics2D Rendering Context
The collection of state attributes associated with a
Graphics2D
object is referred to as theGraphics2D
rendering context . To display text, shapes, or images, you set up theGraphics2D
rendering context and then call one of theGraphics2D
rendering methods, such asdraw
orfill
. TheGraphics2D
rendering context contains attributes that define:To set an attribute in the
Graphics2D
rendering context, you use theset Attribute
methods:When you set an attribute, you pass in the appropriate attribute object. For example, to change the paint attribute to a blue-green gradient fill, you would construct a
GradientPaint
object and then callsetPaint
:gp = new GradientPaint(0f,0f,blue,0f,30f,green); g2.setPaint(gp);
Graphics2D
holds references to its attribute objects--they are not cloned. If you alter an attribute object that is part of theGraphics2D
context, you need to call the appropriateset
method to notify the context. Modifying an attribute object during rendering causes unpredictable behavior.Graphics2D Rendering Methods
Graphics2D
provides general rendering methods that can be used to draw any geometry primitive, text, or image:
draw
--renders the outline of any geometry primitive using the stroke and paint attributes.fill
--renders any geometry primitive by filling its interior with the color or pattern specified by the paint attribute.drawString
--renders any text string. The font attribute is used to convert the string to glyphs and the glyphs are then filled with the color or pattern specified by the paint attribute.drawImage
--renders the specified image.In addition,
Graphics2D
supports theGraphics
rendering methods for particular shapes, such asdrawOval
andfillRect
.
Overview of the Java 2D API |