
Write Backward Text #51
Chapter 7, Text
|
273
HACK
Messing with JLabel
The easiest text component to distort is the simple JLabel. The
BackwardsJLabel class in Example 7-6 subclasses JLabel and uses an
AffineTransform
in the
paint( )
method to do the flip.
The constructors make trivial calls to their parent classes, so the key is the
overridden
paint( ) method. It first checks that you have a Graphics2D and
does the cast. Any
Graphics2D has an AffineTransformation that defines
transforms that are to be applied as the
Graphics2D is rendered. The
AffineTransform of a Component will usually have some important transforms
already defined in it, so it’s best not to replace its transform, but rather to use
the
Graphics2D.transform( ) method to modify the existing AffineTransform
with one of your own making.
But what kind of transform do you want to do? A mirror image consists of
two separate transformations: scaling the x-coordinates by a factor of -1
Example 7-6. Rendering a JLabel as a mirror image
import java.awt.*;
import javax.swing.*;
import java.awt.geom.*;
import javax.swing.text.Document;
public class BackwardsJLabel extends JLabel {
public BackwardsJLabel () { super( ); }
public BackwardsJLabel (Icon image) {super (image);}
public BackwardsJLabel (Icon image, int align) {super (image, align);}
public BackwardsJLabel (String text) { super (text);}
public BackwardsJLabel (String text, Icon icon, int align) ...