Make text space more nature by setting KERNING in Java

Description

The following code shows how to make text space more nature by setting KERNING.

Example


import java.awt.Graphics;
import java.awt.font.TextAttribute;
import java.util.Hashtable;
import java.awt.Font;
import javax.swing.JComponent;
import javax.swing.JFrame;
/*from  w  w  w .  j a v  a2  s .c o  m*/
class MyCanvas extends JComponent {
  public void paint(Graphics g) {
    Hashtable<TextAttribute, Object> map = new Hashtable<TextAttribute, Object>();
    Font font = new Font(Font.SERIF, Font.PLAIN, 24);
    /* Kerning makes the text spacing more natural */
    map.put(TextAttribute.KERNING, TextAttribute.KERNING_ON);
    font = font.deriveFont(map);
    g.setFont(font);
    g.drawString("java2s.com", 45, 60);
  }
}

public class Main {
  public static void main(String[] a) {
    JFrame window = new JFrame();
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.setBounds(30, 30, 450, 450);
    window.getContentPane().add(new MyCanvas());
    window.setVisible(true);
  }
}

The code above generates the following result.

Make text space more nature by setting KERNING in Java




















Home »
  Java Tutorial »
    Graphics »




Animation
BufferedImage
Color
Font
Gradient
Graphics Settings
Image
Mouse Draw
Print
Shape
Text
Transform