Java Reference
In-Depth Information
There's some fabricated text in the last screenshot. In the next chapter we'll add a rather more sophisticated
facility for adding text to a sketch. Don't draw too many masterpieces yet. We won't be able to preserve them
for the nation and posterity by saving them in a file until the chapter after the next.
Summary
In this chapter you have learned how to draw on components and how you can use mouse listeners to
implement a drawing interface. The important points we have covered in this chapter are:
A
Graphics2D
component represents the drawing surface of the component.
❑
You draw on a component by calling methods for its
Graphics2D
object.
❑
The user coordinate system for drawing on a component has the origin in the top-left corner
of the component 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.
❑
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.
❑
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.
❑
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.
❑
The
Graphics2D
class defines methods for drawing outline shapes as well as filled shapes.
❑
The
java.awt.geom
package defines classes that represent 2D shapes.
❑
Exercises
1.
Add the code to the Sketcher program to support drawing an ellipse.
2.
Modify the Sketcher program to include a button for switching fill mode on and off.
3.
Extend the classes defining rectangles, circles and ellipses to support filled shapes.
4.
Extend the curve class to support filled shapes.