
14
|
Chapter 1, Basic JComponents
#3 Fill Your Borders with Pretty Pictures
HACK
H A C K
#3
Fill Your Borders with Pretty Pictures
Hack #3
Swing comes with a set of customizable borders, but sometimes you want
more than they provide. This hack shows how to create a completely image-
based border that can be resized.
Swing has a prefabricated border, called the MatteBorder, which can accept
an image in its constructor. For simple tiled backgrounds, such as a checker-
board pattern, this works fine. However, if you want to have particular
images in each corner, creating a fully resizable image border, then you’ll
need something more powerful. Fortunately, Swing makes it very easy to
create custom border classes. The image border in this hack will produce a
border that looks like Figure 1-12.
The first step to any custom border is to subclass
AbstractBorder and imple-
ment the
paintBorder( ) method. The class will take eight images in the con-
structor, one for each corner and each side; all the code is shown in
Example 1-6.
Figure 1-12. An image-based border
Example 1-6. Building an image-based border
public class ImageBorder extends AbstractBorder {
Image top_center, top_left, top_right;
Image left_center, right_center;
Image bottom_center, bottom_left, bottom_right;
Insets insets;
public ImageBorder(Image top_left, Image top_center, Image top_right,
Image left_center, Image right_center,
Image bottom_left, ...