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) {
super (text, icon, align);
}
public BackwardsJLabel (String text, int align) { super (text, align);}
public void paint (Graphics g) {
if (g instanceof Graphics2D) {
Graphics2D g2 = (Graphics2D) g;
AffineTransform flipTrans = new AffineTransform( );
double widthD = (double) getWidth( );
flipTrans.setToTranslation (widthD, 0);
flipTrans.scale (-1.0, 1);
g2.transform (flipTrans);
super.paint(g);
} else {
super.paint(g);
}
}
}

Get Swing Hacks 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.