O'Reilly logo

Swing Hacks by Chris Adamson, Joshua Marinacci

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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);
}
}
}

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required