Drawing a Drop Shadow

Problem

You want to draw text or graphical objects with a “drop shadow” effect, as in Figure 12-3.

Drop shadow text

Figure 12-3. Drop shadow text

Solution

Draw the component twice, with the darker shadow behind and the “real” color, slightly offset, in front.

Discussion

Program DropShadow does just this. It also uses a Font object from java.awt to exercise some control over the typeface.

The program in Example 12-1 is unabashedly an Applet; to run it, you should invoke it as appletviewer DropShadow.htm [28] (the details of such HTML files are in Section 17.2).

Example 12-1. DropShadow.java

import java.applet.*; import java.awt.*; /** * DropShadow -- show overlapped painting. */ public class DropShadow extends Applet { /** The label that is to appear in the window */ protected String theLabel = null; /** The width and height */ protected int width, height; /** The name of the font */ protected String fontName; /** The font */ protected Font theFont; /** The size of the font */ protected int fontSize = 18; /** The offset for the drop shadow */ protected int theOffset = 3; /** True if we got all required parameters */ protected boolean inittedOK = false; /** Called from the browser to set up. We want to throw various * kinds of exceptions but the API predefines that we don't, so we * limit ourselves to the ubiquitous IllegalArgumentException. */ public void init( ) { // System.out.println("In ...

Get Java Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.