Java Reference
In-Depth Information
• WHAT YOU LEARNED IN THIS CHAPTER
TOPIC
CONCEPT
Device Con-
text
A Graphics2D object represents the drawing surface of a component when the component is displayed
on a device such as a display or printer. This is called a device context.
Drawing on a
Component
You draw on a component by calling methods provided by its Graphics2D object.
Implementing
paint()
You normally draw on a component by implementing its paint() method. The paint() method is
passed a Graphics2D object that is the graphics context for the component but as type Graphics . You
must cast the Graphics object to type Graphics2D to be able to access the Graphics2D class methods.
The paint() method is called whenever the component needs to be redrawn,
Drawing
Coordinate
Systems
The user coordinate system for drawing on a component has the origin in the top-left corner of the com-
ponent by default, with the positive x -axis from left to right, and the positive y -axis from top to bottom.
This is automatically mapped to the device coordinate system, which is in the same orientation.
Obtaining a
Graphics
Context
You can't create a Graphics2D object. If you want to draw on a component outside of the paint()
method, you can obtain a Graphics2D object for the component by calling its getGraphics() method.
Drawing
Modes
There is more than one drawing mode that you can use. The default mode is paint mode, where drawing
overwrites the background pixels with pixels of the current color. Another mode is XOR mode, where
the current color is combined with the background color. This is typically used to alternate between the
current color and a color passed to the setXORMode() method.
Defining
Geometric
Shapes
The java.awt.geom package defines classes that represent 2D shapes.
Drawing
Geometric
Shapes
The Graphics2D class defines methods for drawing outline shapes as well as filled shapes.
Drawing
Using the
Mouse
You can create mechanisms for drawing on a component using the mouse by implementing methods that
handle mouse events.
Search WWH ::




Custom Search