3/18/08

Shadow Text Effect on JLabel

I found the trick to create shawdow text on JLabel from java forum. Instead of use JLabel.setText() set string to JLabel, he create Image and get Graphics2D by Image.createGraphics(). Then use TextLayout draw overlapping string on that Graphics2D.
example code

        int w = 500;
int h = 120;
Font font = new Font("Lucida Bright", Font.ITALIC, 72);
String text = "Shadow Text";

BufferedImage image = new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB);
Graphics2D g = image.createGraphics();
adjustGraphics(g);

//start off all white:
g.setPaint(Color.WHITE);
g.fillRect(0, 0, w, h);

//draw "shadow" text: to be blurred next
TextLayout textLayout = new TextLayout(text, font, g.getFontRenderContext());
g.setPaint(new Color(128,128,255));
textLayout.draw(g, 15, 105);
g.dispose();

//blur the shadow: result is sorted in image2
float ninth = 1.0f / 9.0f;
float[] kernel = {ninth, ninth, ninth, ninth, ninth, ninth, ninth, ninth, ninth};
ConvolveOp op = new ConvolveOp(new Kernel(3, 3, kernel), ConvolveOp.EDGE_NO_OP, null);
BufferedImage image2 = op.filter(image,null);

//write "original" text on top of shadow
Graphics2D g2 = image2.createGraphics();
adjustGraphics(g2);
g2.setPaint(Color.BLACK);
textLayout.draw(g2, 10, 100);
....
private void adjustGraphics(Graphics2D g) {
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS,
RenderingHints.VALUE_FRACTIONALMETRICS_ON);
}


Last use JLabel.setIcon(new ImageIcon(image2)) to display text with a shadow. Lower label is created by method show here, the result is look very good to me.

1 comments:

Javadeveloper said...

Hi,

in an attempt to display two images between text in a jlabel... the paintcomponent method fails to display the items. kindly assist me in this attempt.

Thanks