
Add a Watermark to a Text Component #5
Chapter 1, Basic JComponents
|
23
HACK
H A C K
#5
Add a Watermark to a Text Component
Hack #5
This hack will show how to create a custom image background for the
JTextField, a complex Swing component that does not already support
backgrounds or icons by default.
One of Swing’s most underused features is the ability to partially override
drawing code. Most programs enhance widgets by using renderers or com-
pletely overriding the paint code. By only partially overriding the drawing,
however, you can create some very interesting effects that blend both new
and existing drawing commands.
Some components, like
JList and JTable, use renderers to customize their
look. To put a background in a
JTextField, however, requires more. The
plan is to subclass
JTextField, prepare the resources for drawing a back-
ground (loading the image, etc.), and then draw a new background while
preserving the normal
JTextField drawing code for the text and cursor.
The actual drawing will be done with a
TexturePaint. Java2D allows you to
fill any area with instances of the
Paint interface. Typically you use a color,
which is an implementation of
Paint, but it is possible to use something else,
such as a texture or gradient. This class will use a
TexturePaint to tile an
image across the component’s background.
The first step is to create a
JTextField subclass (shown in Example 1-10).
Example 1-10 creates ...