Label with large font and ANTIALIAS paint : Label « Swing Components « Java

Label with large font and ANTIALIAS paint

Swing Hacks Tips and Tools for Killer GUIs
By Joshua Marinacci, Chris Adamson
First Edition June 2005  
Series: Hacks
ISBN: 0-596-00907-0
Pages: 542
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.font.LineMetrics;

import javax.swing.JFrame;
import javax.swing.JLabel;

public class RichJLabel extends JLabel {

  private int tracking;

  public RichJLabel(String text, int tracking) {
    this.tracking = tracking;

  private int left_x, left_y, right_x, right_y;

  private Color left_color, right_color;

  public void setLeftShadow(int x, int y, Color color) {
    left_x = x;
    left_y = y;
    left_color = color;

  public void setRightShadow(int x, int y, Color color) {
    right_x = x;
    right_y = y;
    right_color = color;

  public Dimension getPreferredSize() {
    String text = getText();
    FontMetrics fm = this.getFontMetrics(getFont());

    int w = fm.stringWidth(text);
    w += (text.length() - 1) * tracking;
    w += left_x + right_x;

    int h = fm.getHeight();
    h += left_y + right_y;

    return new Dimension(w, h);

  public void paintComponent(Graphics g) {
    ((Graphics2D) g).setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,

    char[] chars = getText().toCharArray();

    FontMetrics fm = this.getFontMetrics(getFont());
    int h = fm.getAscent();
    LineMetrics lm = fm.getLineMetrics(getText(), g);

    int x = 0;

    for (int i = 0; i < chars.length; i++) {
      char ch = chars[i];
      int w = fm.charWidth(ch) + tracking;

      g.drawString("" + chars[i], x - left_x, h - left_y);

      g.drawString("" + chars[i], x + right_x, h + right_y);

      g.drawString("" + chars[i], x, h);

      x += w;


  public static void main(String[] args) {
    RichJLabel label = new RichJLabel("", 0);
    label.setLeftShadow(1, 1, Color.white);
    label.setRightShadow(1, 1, Color.white);

    JFrame frame = new JFrame("RichJLabel hack");

  public static void p(String str) {


Related examples in the same category

1.MultiLine Label
2.Multi Line Label extends JComponent
3.Multi Line Label extends JPanel
4.Link Label
5.Vertical Label UI
6.Label 3D
7.URL Label
8.Hyperlink Label
9.Bevel TextBevel Text
10.A JLabel that can be underlined, implements Scrollable
11.Gradient Label
12.Hyperlink Label 2
13.Computes a reasonable set of labels for a data interval and number of labels.
14.Multi-label Label
15.Shadow Label
16.Button Label