Java Reference
In-Depth Information
methods like
drawString()
have extremely good aim, make it very easy to create a drop
shadow and to combine graphics drawings in interesting ways.
Remember to draw from the back to the front, though. To see why, try interchanging the two
calls to
drawString()
in the previous code.
A word of warning: don't mix drawing with added GUI components (see
Chapter 14
). For
example, say you had a
paint()
method in an applet or other container and had
add()
ed a
button to it. This works on some implementations of Java, but not on others: only the paint-
ing or the button appears, not both. It's not portable, so don't do it—you've been warned! In-
stead, you should probably use multiple components; see the
JFrame
's
getContentPane()
An alternative method of obtaining a drop shadow effect is covered in
Drawing Text with
Drawing Text with 2D
Problem
You want fancier drawing abilities.
Solution
Use a
Graphics2D
object.
Discussion
The 2D graphics could be the subject of an entire book, and in fact, it is.
Java 2D Graphics
by Jonathan Knudsen (O'Reilly) covers every imaginable aspect of this comprehensive
graphics package. Here I'll just show one example: drawing text with a textured background.
The
Graphics2D
class is a direct subclass of the original Java
Graphics
object. In fact, your
paint()
method is always called with an instance of
Graphics2D
. So begin your paint meth-
od by casting appropriately:
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;